Halo
发布于 2022-08-05 / 113 阅读 / 0 评论 / 0 点赞

json 和 class 互转

  1. 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)
  1. 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
  1. class instance to json
json_data = json.dumps(person_object.__dict__)
print(json_data)

评论