JSON Deserialization of nested NamedTuples in Python

Viewed 553

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')
1 Answers

You might want to look into pydantic which has a lot of functionalities for serializing and deserializing objects. It also allows objects to be set as immutable, see here.

Related