Menu Close

How to convert JSON data into a Python object?

Sometimes, we want to convert JSON data into a Python object.

In this article, we’ll look at how to convert JSON data into a Python object.

How to convert JSON data into a Python object?

To convert JSON data into a Python object, we can use the json.loads method.

For instance, we write

import json
from types import SimpleNamespace

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

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

to call json.loads with data to parse the data JSON string into a dict.

We set the object_hook argument to a function that returns a SimpleNamespace object to convert the dict into a Python object.

Then we can access dict values from x like x.hometown.name.

Conclusion

To convert JSON data into a Python object, we can use the json.loads method.

Posted in Python, Python Answers