- json to object
import json
from types import SimpleNamespace
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
print(x.name, x.hometown.name, x.hometown.id)
- json to class instance
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
# Must be exactly the same as the member variables of the class, no more or no less
person_string = '{"name": "Bob", "age": 25}'
person_dict = json.loads(person_string)
person_object = Person(**person_dict)
print(person_object)
<__main__.Person object at 0x7fc61cac5978>
print(person_object.name)
Bob
- class instance to json
json_data = json.dumps(person_object.__dict__)
print(json_data)