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