Jsons
Jsons is a Python library designed for seamlessly serializing complex Python objects (including dataclasses, attrs, and POPOs) to JSON (dicts or strings) and deserializing them back. It aims for minimal effort, requiring no modifications to your objects, and is highly customizable and extendable. The current version is 1.6.3, and it maintains an active release cadence with several minor updates per year addressing features and bug fixes.
Warnings
- gotcha Do not confuse `jsons` with Python's built-in `json` module. While `json` handles basic types, `jsons` is designed for direct serialization/deserialization of complex Python objects (like dataclasses, attrs, and custom classes) without manual encoding/decoding for types like `datetime` or custom objects.
- breaking In `jsons` v1.5.0, microseconds are no longer stripped by default when serializing `datetime` objects. This changes the output format for datetimes if your application previously relied on microseconds being removed.
- gotcha Prior to v1.6.3, `jsons` could unintentionally parse a string into a `datetime` object during deserialization, leading to incorrect type assignments.
- gotcha Prior to v1.6.1, `IntEnums` were not serialized with their names even when `use_enum_name=True` was intended, potentially serializing by value instead. Named tuples also had issues with `typing.get_type_hints`, affecting future annotations.
Install
-
pip install jsons
Imports
- jsons
import jsons
Quickstart
import jsons
from dataclasses import dataclass
from datetime import datetime, timezone
import os
@dataclass
class Person:
name: str
birthday: datetime
email: str = os.environ.get('USER_EMAIL', 'default@example.com')
# Example data
birthday_guido = datetime(1956, 1, 31, 12, 0, tzinfo=timezone.utc)
p = Person('Guido van Rossum', birthday_guido)
# Serialization to a dictionary
out_dict = jsons.dump(p)
print(f"Serialized dict: {out_dict}")
# Deserialization from a dictionary back to an object
p2 = jsons.load(out_dict, Person)
print(f"Deserialized object: {p2}")
assert p == p2
# Example with a list of custom objects
@dataclass
class Pet:
name: str
species: str
@dataclass
class Owner:
name: str
pets: list[Pet]
o = Owner('Alice', [Pet('Rex', 'dog'), Pet('Whiskers', 'cat')])
owner_dict = jsons.dump(o)
print(f"Serialized owner: {owner_dict}")
o2 = jsons.load(owner_dict, Owner)
print(f"Deserialized owner: {o2}")
assert o == o2