JSON Serialization of nested NamedTuples is straightforward:
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? I thought using a recursive function but I was hoping there would be a cleaner implementation…
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')