简体   繁体   English

用json序列化另一个对象中的Python对象?

[英]Serialize Python object in another object with json?

how can I serialize an object which has another object in his attributes using TinyDB ?如何使用 TinyDB 序列化在其属性中具有另一个对象的对象?

class address:
    def __init__(self, country, city):
        self.country = country
        self.city = city


class Person:
    def __init__(self, name, address):
        self.name = name
        self.address = address


add = Address("USA", "New York")
person = Person("John", add)

Now, when I try to serialize person I got this error:现在,当我尝试序列化person时,我收到了这个错误:

TypeError: Object of type Address is not JSON serializable

I know that JSON can't serialize objects and I have to convert them to dicts before that.我知道 JSON 不能序列化对象,我必须在此之前将它们转换为 dicts。 I can do it for a simple object like that:我可以为这样的简单对象做到这一点:

from tinydb import TinyDB

db = TinyDB


serialized_address = {"country": self.country, "city": self.city}

db.insert(serialized_address)

But how am I supposed to do this when there is an instance in another instance ?但是当另一个实例中有一个实例时我应该怎么做呢? (I'm forced to use TinyDB and JSON for my project...) (我被迫在我的项目中使用 TinyDB 和 JSON ......)

The only clue I have, is to put a reference of the first object instead of the object itself, in the second object arguments, but I can't figure out how to do that...我唯一的线索是在第二个对象参数中放置第一个对象而不是对象本身的引用,但我不知道该怎么做......

One option is to convert any existing classes into dataclasses , which are just normal classes with some autogenerated methods like __init__ and __repr__ for example.一种选择是将任何现有的类转换为dataclasses ,它们只是具有一些自动生成的方法的普通类,例如__init____repr__

Then, you can recursively serialize a nested dataclass model using the asdict helper function that dataclasses provides:然后,您可以使用dataclasses提供的asdict辅助函数递归地序列化嵌套的数据类模型:

from dataclasses import dataclass, asdict


@dataclass
class Person:
    name: str
    address: 'Address'


@dataclass
class Address:
    country: str
    city: str


add = Address("USA", "New York")
person = Person("John", add)

serialized = asdict(person)
print(serialized)
# {'name': 'John', 'address': {'country': 'USA', 'city': 'New York'}}

If you need to work with more complex types like datetime , or else need to load or de-serialize json to a dataclass model, I would check out a de/serialization library like the dataclass-wizard , which can help further simplify this process:如果您需要使用更复杂的类型,例如datetime ,或者需要将 json 加载或反序列化到数据类模型,我会查看像dataclass-wizard这样的反序列化库,它可以帮助进一步简化这个过程:

from dataclasses import dataclass
from datetime import date

from dataclass_wizard import fromdict, asdict


@dataclass
class Person:
    name: str
    address: 'Address'
    birth_date: date


@dataclass
class Address:
    country: str
    city: str


person = fromdict(Person, {'name': 'John', 'BirthDate': '1990-01-01', 'address': {'country': 'USA', 'city': 'New York'}})

print(person)
# Person(name='John', address=Address(country='USA', city='New York'), birth_date=datetime.date(1990, 1, 1))

serialized = asdict(person)
print(serialized)
# {'name': 'John', 'address': {'country': 'USA', 'city': 'New York'}, 'birthDate': '1990-01-01'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM