Python Answers

How to convert JSON data into a Python object?

Spread the love

To convert JSON data into a Python object?, we can use the SimpleNamespace class.

For instance, we write

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))

to call json.loads to load the data into a dictionary.

And then we set object_hook to a lambda function that takes dictionary d and convert it to an object with the SimpleNamespace class.

Then we can access the data values from the object with,,

as we have in print.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *