A comprehensive Python library for serializing and deserializing Python objects to and from JSON (dictionaries) with minimal code changes required.
81
Primary functions for converting Python objects to JSON-compatible formats and vice versa. These functions handle automatic type detection, nested objects, and provide extensive customization options.
def dump(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
"""
Serialize the given Python object to a JSON equivalent type (dict, list, int, str, etc.).
Parameters:
- obj: Any Python instance to be serialized
- cls: Optional type to serialize obj as (must have __slots__ defined)
- strict: Bool to determine if serializer should be strict (only dump known attributes)
- fork_inst: Optional fork instance for separate serializer configuration
- **kwargs: Additional keyword arguments passed to serializer functions
Returns:
JSON-compatible Python object (dict, list, str, int, float, bool, None)
"""
def dumps(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
"""
Serialize the given Python object to a JSON string.
Parameters:
- obj: Any Python instance to be serialized
- cls: Optional type to serialize obj as
- strict: Bool for strict serialization mode
- fork_inst: Optional fork instance
- **kwargs: Additional arguments including JSON formatting options
Returns:
str: JSON string representation of the object
"""
def dumpb(obj, cls=None, *, strict=False, fork_inst=None, **kwargs):
"""
Serialize the given Python object to JSON bytes.
Parameters:
- obj: Any Python instance to be serialized
- cls: Optional type to serialize obj as
- strict: Bool for strict serialization mode
- fork_inst: Optional fork instance
- **kwargs: Additional arguments including encoding options
Returns:
bytes: JSON bytes representation of the object
"""def load(json_obj, cls=None, *, strict=False, fork_inst=None, attr_getters=None, **kwargs):
"""
Deserialize the given JSON object to a Python object of the specified type.
Parameters:
- json_obj: JSON-compatible object (dict, list, str, int, float, bool, None)
- cls: Target Python type to deserialize into
- strict: Bool for strict deserialization mode
- fork_inst: Optional fork instance
- attr_getters: Dict mapping attribute names to getter functions
- **kwargs: Additional arguments passed to deserializer functions
Returns:
Instance of cls type reconstructed from json_obj
Raises:
- DeserializationError: If json_obj cannot be deserialized to cls
- ValidationError: If validation fails on the deserialized object
"""
def loads(s, cls=None, *, strict=False, fork_inst=None, **kwargs):
"""
Deserialize a JSON string to a Python object of the specified type.
Parameters:
- s: JSON string to deserialize
- cls: Target Python type to deserialize into
- strict: Bool for strict deserialization mode
- fork_inst: Optional fork instance
- **kwargs: Additional arguments including JSON parsing options
Returns:
Instance of cls type reconstructed from JSON string
Raises:
- DecodeError: If JSON string is malformed
- DeserializationError: If deserialization fails
"""
def loadb(b, cls=None, *, strict=False, fork_inst=None, **kwargs):
"""
Deserialize JSON bytes to a Python object of the specified type.
Parameters:
- b: JSON bytes to deserialize
- cls: Target Python type to deserialize into
- strict: Bool for strict deserialization mode
- fork_inst: Optional fork instance
- **kwargs: Additional arguments including encoding options
Returns:
Instance of cls type reconstructed from JSON bytes
Raises:
- DecodeError: If JSON bytes are malformed
- DeserializationError: If deserialization fails
"""import jsons
from dataclasses import dataclass
from typing import List
from datetime import datetime
@dataclass
class Task:
title: str
completed: bool
due_date: datetime
@dataclass
class Project:
name: str
tasks: List[Task]
# Create complex nested objects
project = Project(
name="Website Redesign",
tasks=[
Task("Design mockups", False, datetime(2023, 12, 15)),
Task("Implement frontend", False, datetime(2023, 12, 30))
]
)
# Serialize to JSON-compatible dict
project_dict = jsons.dump(project)
print(project_dict)
# {
# 'name': 'Website Redesign',
# 'tasks': [
# {'title': 'Design mockups', 'completed': False, 'due_date': '2023-12-15T00:00:00'},
# {'title': 'Implement frontend', 'completed': False, 'due_date': '2023-12-30T00:00:00'}
# ]
# }
# Serialize to JSON string
project_json = jsons.dumps(project, indent=2)
print(project_json) # Pretty-printed JSON string
# Serialize to JSON bytes
project_bytes = jsons.dumpb(project)
print(type(project_bytes)) # <class 'bytes'>import jsons
from dataclasses import dataclass
from typing import List
@dataclass
class User:
name: str
age: int
emails: List[str]
# Deserialize from dict
user_data = {
'name': 'John Doe',
'age': 30,
'emails': ['john@example.com', 'john.doe@work.com']
}
user = jsons.load(user_data, User)
print(user.name) # "John Doe"
print(user.emails[0]) # "john@example.com"
# Deserialize from JSON string
user_json = '{"name": "Jane Smith", "age": 25, "emails": ["jane@example.com"]}'
user = jsons.loads(user_json, User)
print(user.name) # "Jane Smith"
# Deserialize from JSON bytes
user_bytes = b'{"name": "Bob Wilson", "age": 35, "emails": []}'
user = jsons.loadb(user_bytes, User)
print(user.age) # 35import jsons
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
# Extra fields are normally ignored
person_data = {'name': 'Alice', 'age': 30, 'extra_field': 'ignored'}
person = jsons.load(person_data, Person) # Works fine
# Strict mode raises an error for extra fields
try:
person = jsons.load(person_data, Person, strict=True)
except jsons.DeserializationError as e:
print(f"Strict mode error: {e}")import jsons
from decimal import Decimal
from datetime import datetime
from uuid import UUID
# jsons handles many built-in types automatically
data = {
'price': Decimal('19.99'),
'created_at': datetime.now(),
'id': UUID('12345678-1234-5678-1234-567812345678')
}
# Serialize complex types
serialized = jsons.dump(data)
print(serialized)
# {
# 'price': '19.99',
# 'created_at': '2023-12-01T10:30:00.123456',
# 'id': '12345678-1234-5678-1234-567812345678'
# }
# Deserialize back with proper types
original_data = jsons.load(serialized, dict)
print(type(original_data['price'])) # <class 'str'> (needs type hint for proper restoration)Install with Tessl CLI
npx tessl i tessl/pypi-jsonsdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10