jam.utils.json.codec
Core JSON serialization engine that handles type-safe conversion between JAM types and JSON.
Type Resolution
Type Resolution Order
None type checking
Primitive type validation
Optional type unwrapping
Container type handling
Dataclass field processing
Custom type conversion
Type Mapping
Primitive Types:
bool -> true/false
int -> number
str -> string
bytes -> hex string
Null -> null
Container Types:
Array[T] -> [T, …]
Vector[T] -> [T, …]
Dict[K,V] -> {K: V, …}
Option[T] -> T | null
Enum -> value | name
Custom Types:
@json_serializable -> object
JsonSerde -> custom conversion
Implementation Details
Type Conversion
The codec processes types in this order:
None values -> null
Primitive types -> direct conversion
Sequences -> JSON arrays
Mappings -> JSON objects
Dataclasses -> JSON objects with field processing
Objects with value property -> convert value
Objects with to_json() -> custom conversion
Field Processing
For dataclasses, fields are processed with:
Type validation
Custom field names
Null value handling
Value formatting
Default value handling
Error Handling
Exception Types
JsonSerializationError: Base serialization error
JsonDeserializationError: Base deserialization error
JsonFieldError: Field-specific errors
Common Error Cases
Type mismatch during deserialization
Missing required fields
Invalid field values
Unsupported types
API Reference
JsonCodec
- class jam.utils.json.codec.JsonCodec[source]
Bases:
objectCore JSON serialization engine.
- static from_json(data: Any, target_type: Type[T]) T[source]
Convert JSON-compatible value to target type.
Functions
Examples
Basic Usage
from jam.utils.json import JsonCodec
# Primitive types
JsonCodec.to_json(42) # -> 42
JsonCodec.to_json("hello") # -> "hello"
JsonCodec.to_json(True) # -> true
# Container types
JsonCodec.to_json([1, 2, 3]) # -> [1, 2, 3]
JsonCodec.to_json({"a": 1}) # -> {"a": 1}
Dataclass Handling
@dataclass
class Point:
x: int
y: int
point = Point(1, 2)
data = JsonCodec.to_json(point) # -> {"x": 1, "y": 2}
decoded = JsonCodec.from_json(data, Point) # -> Point(x=1, y=2)
Custom Types
class Vector:
def __init__(self, x, y):
self.value = {"x": x, "y": y}
vec = Vector(1, 2)
data = JsonCodec.to_json(vec) # -> {"x": 1, "y": 2}
Error Handling
try:
JsonCodec.from_json("not a dict", Point)
except JsonDeserializationError as e:
print(e) # Expected dict for Point, got str