简体   繁体   English

JSON Python中嵌套的NamedTuples的反序列化

[英]JSON Deserialization of nested NamedTuples in Python

JSON Serialization of nested NamedTuples is straightforward: JSON 嵌套的 NamedTuples 的序列化很简单:

import json
from typing import NamedTuple

class A(NamedTuple):
    a: int
class B(NamedTuple):
    a: A
    b: str
s = json.dumps(B(A(42), "auie"))
print(s) # outputs the following string: "[[42], 'auie']"

JSON Deserialization, on the other hand, requires some work… What would be the best approach? JSON 另一方面,反序列化需要一些工作……最好的方法是什么? I thought using a recursive function but I was hoping there would be a cleaner implementation…我想使用递归 function 但我希望会有一个更清晰的实现......

def deserialize(T,l):
    for i, k in enumerate(T._field_types):
        if hasattr(T._field_types[k], "_field_types"): # I'm open to a more robust check
            l[i] = deserialize(T._field_types[k], l[i])
    return T(*l)
    
print(deserialize(B, json.loads(s))) # prints B(a=A(a=42), b='auie')

You might want to look into pydantic which has a lot of functionalities for serializing and deserializing objects.你可能想看看pydantic ,它有很多用于序列化和反序列化对象的功能。 It also allows objects to be set as immutable, see here .它还允许将对象设置为不可变的,请参见此处

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

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