typing-json
raw JSON → 0.1.3 verified Sat May 09 auth: no python
Type-aware Python JSON serialization and validation. Provides decorators and functions to encode/decode Python objects with type hints, with support for Union, Optional, and nested dataclasses. Current version 0.1.3, released 2023; low release cadence.
pip install typing-json Common errors
error TypeError: Object of type <class '...'> is not JSON serializable ↓
cause The type is not a dataclass, a primitive, or registered. The library cannot serialize it.
fix
Convert the object to a dataclass or use
to_json on a supported type. If it's a custom class, consider using the @json decorator (see docs). error typing_json.errors.ValidationError: Expected type <class 'int'>, got <class 'str'> ↓
cause The JSON value for a field does not match the declared type hint (e.g., string in an int field).
fix
Check the input JSON and ensure it conforms to the expected types. For optional fields, ensure
null is allowed. Warnings
gotcha Union types are only supported if the alternatives are distinct types (e.g., int vs str). If multiple types share the same base or are ambiguous (e.g., Union[int, float]), deserialization may fail or produce wrong type. ↓
fix Use explicit discriminators or avoid ambiguous Union types. For numbers, prefer the broader type (e.g., float).
deprecated The function `to_json` defaults to `ensure_ascii=False`, which may produce non-ASCII characters. Future versions may change this. ↓
fix Always pass `ensure_ascii=True` if you need ASCII-only JSON, or rely on current default but be aware it might change.
gotcha Nested dataclasses are supported, but only if all fields are serializable. If a field is a custom class without type hints, serialization fails silently or raises TypeError. ↓
fix Ensure all nested objects are dataclasses or have registered serializers. Use `@json` decorator from `typing_json` library (experimental) for plain classes.
Imports
- to_json wrong
from typing_json.serializer import to_jsoncorrectfrom typing_json import to_json - from_json
from typing_json import from_json
Quickstart
from dataclasses import dataclass
from typing import Optional
from typing_json import to_json, from_json
@dataclass
class Person:
name: str
age: int
email: Optional[str] = None
# Serialize
person = Person('Alice', 30)
json_str = to_json(person)
print(json_str) # '{"name": "Alice", "age": 30, "email": null}'
# Deserialize
person2 = from_json(json_str, Person)
print(person2) # Person(name='Alice', age=30, email=None)