Python Programming Tips

The best approach to serialise/deserialise between Python items and JSON — Attr and Cattr

Photo via JoshuaWoroniecki on Pixabay
pip set up attrs
pip set up cattrs
from attr import attrs, attrib
import cattr
Photo via Free-Photos on Pixabay
from typing import Tuplecattr.construction([1.01, True, False, "2", "I will be ignored"], Tuple[int, int, int, int])
Photo via PublicDomainPictures on Pixabay
@attrs
magnificence Person:
identify = attrib()
age = attrib()
def tell_age(self):
print(f'My identify is {self.identify} and my age is {self.age}.')
from attr import asdictp1 = Person('Chris', 32)
asdict(p1)
cattr.unstructure(p1)
p2 = cattr.construction({'identify': 'Chelsea', 'age': 1}, Person)
Photo via josephredfield on Pixabay
p_list_raw = [
{'identify': 'Alice', 'age': 20},
{'identify': 'Bob', 'age': 25},
{'identify': 'Chris', 'age': 32}
]
from typing import Listp_list = cattr.construction(p_list_raw, List[Person])
Photo via SCY on Pixabay
import jsonjson_obj = json.dumps(cattr.unstructure(p_list))
print(json_obj)
p_list = cattr.construction(json.lots(json_obj), List[Person])
Photo via geralt on Pixabay

LEAVE A REPLY

Please enter your comment!
Please enter your name here