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))
print(x.name, x.hometown.name, x.hometown.id)
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
x.name, x.hometown.name, x.hometown.id
as we have in print
.