JSON is a popular message interchange format employed in API design for its simplicity, readability, flexibility and wide support. However, json.dump and json.load offer no direct support when working with Python data classes employing type annotations. This package offers services for working with strongly-typed Python classes: serializing objects to JSON, deserializing JSON to objects, and producing a JSON schema that matches the data class, e.g. to be used in an OpenAPI specification.
Unlike orjson, this package supports both serializing and deserializing complex types such as data classes, UUIDs, decimals, etc., and allows specifying custom serialization and deserialization hooks. It doesn't require introducing custom classes in your class inheritance chain (such as BaseModel in Pydantic data classes), making it suitable for operating on classes defined in third-party modules.
Features
This package offers the following services:
JSON serialization and de-serialization
Generate a JSON object from a Python object (serialization.object_to_json)
Parse a JSON object into a Python object (serialization.json_to_object)
JSON schema
Generate a JSON schema from a Python type (schema.classdef_to_schema)
Validate a JSON object against a Python type (schema.validate_object)
Type information
Extract documentation strings (a.k.a. docstring) from types (docstring.parse_type)
Inspect types, including generics (package inspection)
These services come with full support for complex types like data classes, named tuples and generics.
In the context of this package, a JSON object is the (intermediate) Python object representation produced by json.loads from a JSON string. In contrast, a JSON string is the string representation generated by json.dumps from the (intermediate) Python object representation.
Use cases
Writing a cloud function (lambda) that communicates with JSON messages received as HTTP payload or websocket text messages
Verifying if an API endpoint receives well-formed input
Generating a type schema for an OpenAPI specification to impose constraints on what messages an API can receive (see )
Fixed-width integer (e.g. uint64) and floating-point (e.g. float32) types are annotated types defined in the package strong_typing.auxiliary. Their signature is recognized when generating a schema, and a format property is written instead of minimum and maximum constraints.
If a composite object (e.g. a data class or a plain Python class) has a to_json member function, then this function is invoked to produce a JSON object representation from an instance.
If a composite object has a from_json class function (a.k.a. @classmethod), then this function is invoked, passing the JSON object as an argument, to produce an instance of the corresponding type.
Custom types
It is possible to declare custom types when generating a JSON schema. For example, the following class definition has the annotation @json_schema_type, which will register a JSON schema subtype definition under the path #/definitions/AzureBlob, which will be referenced later with $ref:
You can use @json_schema_type without the schema parameter to register the type name but have the schema definition automatically derived from the Python type. This is useful if the type is reused across the type hierarchy:
@json_schema_type
class Image: ...
class Study:
left: Image
right: Image
Here, the two properties of Study (left and right) will refer to the same subtype #/definitions/Image.
Union types
Serializing a union type entails serializing the active member type.
De-serializing discriminated (tagged) union types is based on a disjoint set of property values with type annotation Literal[...]. Consider the following example:
@dataclass
class ClassA:
name: Literal["A", "a"]
value: str
@dataclass
class ClassB:
name: Literal["B", "b"]
value: str
Here, JSON representations of ClassA and ClassB are indistinguishable based on property names alone. However, the property name for ClassA can only take values "A" and "a", and property name for ClassB can only take values "B" and "b", hence a JSON object such as
{ "name": "A", "value": "string" }
uniquely identifies ClassA, and can never match ClassB. The de-serializer can instantiate the appropriate class, and populate properties of the newly created instance.
Tagged union types must have at least one property of a literal type, and the values for that type must be all different.
When de-serializing regular union types that have no type tags, the first successfully matching type is selected. It is a parse error if all union member types have been exhausted without a finding match.
Name mangling
If a Python class has a property augmented with an underscore (_) as per PEP 8 to avoid conflict with a Python keyword (e.g. for or in), the underscore is removed when reading from or writing to JSON.
Alternatives
Use instead of json-strong-typing: tools that do the same job, closest first.