Jsons

1.6.3 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to define a dataclass and use `jsons.dump()` to serialize an instance into a dictionary and `jsons.load()` to deserialize it back. It also includes an example with nested objects and lists, showcasing `jsons`'s ability to handle complex type hints.

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

view raw JSON →