recursively deserialize attributes
dynofu opened this issue · 0 comments
dynofu commented
import attr
from attrs_serde import serde
name_path = ["contact", "personal", "Name"]
phone_path = ["contact", "Phone"]
@serde
@attr.s(auto_attribs=True, frozen=True)
class Name:
first: str
last: str
@serde
@attr.s(auto_attribs=True, frozen=True)
class Person:
name: Name = attr.ib(metadata={"to": name_path, "from": name_path})
phone: str = attr.ib(metadata={"to": phone_path, "from": phone_path})
person_json = {"contact": {"personal": {"Name": {"first": "John", "last": "Smith"}}, "Phone": "555-112233"}}
# to/from only works on serde
p = Person(name=Name(first="John", last="Smith"), phone="555-112233")
print(p.to_dict())
# {'contact': {'personal': {'Name': {'first': 'John', 'last': 'Smith'}}, 'Phone': '555-112233'}}
p1 = Person.from_dict(person_json)
print(f"p1={p1}") # <---
# p1=Person(name={'first': 'John', 'last': 'Smith'}, phone='555-112233')
cattrs does the recursive right, but lack of attribute mapping.
attrs-serde has the mapping but does not do recursive deserialization.