For serializing Python objects to JSON (dicts) and back
💗 this lib? Leave a ★ and tell your colleagues!
Example of a model to serialize:
>>> @dataclass
... class Person:
... name: str
... birthday: datetime
...
>>> p = Person('Guido van Rossum', birthday_guido)
Example of using jsons to serialize:
>>> out = jsons.dump(p)
>>> out
{'birthday': '1956-01-31T12:00:00Z', 'name': 'Guido van Rossum'}
Example of using jsons to deserialize:
>>> p2 = jsons.load(out, Person)
>>> p2
Person(name='Guido van Rossum', birthday=datetime.datetime(1956, 1, 31, 12, 0, tzinfo=datetime.timezone.utc))
pip install jsons
import jsons
some_instance = jsons.load(some_dict, SomeClass) # Deserialization
some_dict = jsons.dump(some_instance) # Serialization
In some cases, you have instances that contain other instances that need (de)serialization, for instance with lists or dicts. You can use the
typing
classes for this as is demonstrated below.
from typing import List, Tuple
import jsons
# For more complex deserialization with generic types, use the typing module
list_of_tuples = jsons.load(some_dict, List[Tuple[AClass, AnotherClass]])
(For more examples, see the FAQ)
fork_inst
s were not propagated in default_list_deserializer
(thanks to patrickguenther).use_enum_name=True
(thanks to georgeharker).typing.get_type_hints
for getting the types, causing trouble in future annotations (thanks to georgeharker).attrs
.ZoneInfo
failed to dump if attached to a datetime
.ZoneInfo
on Python3.9+.dict[str, str]
).warn_on_fail
parameter to default_list_deserializer
that allows to continue deserialization upon errors.transform
that can transform an object to an object of another type.pathlib.Path
(thanks to alexmirrington).__annotations__
in favor _field_types
because of deprecation as of 3.8.__version__
which can be imported from jsons
Union
types.JsonSerializable
always dumped their attributes as if in strict mode.strict
parameter to dump
to indicate that dumping a certain cls
will ignore any extra data.dump(obj, cls=x)
, x
can now be any class (previously, only a class with __slots__
).Decimal
(thanks to herdigiorgi).dump(5, str)
).dump(obj, List[str])
) will now dump with respect to that types (if strict
)default_dict
serializer now optionally accepts types: Optional[Dict[str, type]]
.strict=True
(up to 4 times faster!).set_validator
with multiple types did not work.time
.timezone
.timedelta
.date
.Dict[K, V]
).List
(no generic type) failed.Dict
(no generic type) failed.Tuple
(no generic type) failed.Special thanks to the following contributors of code, discussions or suggestions:
patrickguenther, davetapley, pietrodn, georgeharker, aecay, bibz, thijss, alexmirrington, tirkarthi, marksomething, herdigiorgi, jochembroekhoff, robinklaassen, ahmetkucuk, casparjespersen, cypreess, gastlich, jmolinski, haluzpav, finetuned89