Skip to content

Json Codec

JSON Encoder/Decoder — tools/json_codec.py

Section titled “JSON Encoder/Decoder — tools/json_codec.py”

A focused JSON encoder/decoder for axon-web, providing a testable artifact for the upcoming M14 HTTP server contract.

encode(obj, *, indent=None, sort_keys=False) -> str

Section titled “encode(obj, *, indent=None, sort_keys=False) -> str”

Encode a Python object to a JSON string.

  • Strict validation: rejects NaN, Infinity, and non-serializable types
  • Raises: JsonEncodeError on failure
  • Parameters:
    • indent: Pretty-print indent level (None for compact)
    • sort_keys: Sort dictionary keys alphabetically

Decode a JSON string/bytes to a Python object.

  • Raises: JsonDecodeError on malformed input
  • Parameters:
    • s: JSON string or bytes

Streaming encoder — yields JSON chunks for large objects.

timed_encode(obj, **kwargs) -> tuple[str, float]

Section titled “timed_encode(obj, **kwargs) -> tuple[str, float]”

Encode with timing — returns (json_str, duration_ms).

Decode with timing — returns (obj, duration_ms).

Return codec diagnostics (version, stdlib version).

ClassBaseDescription
JsonErrorValueErrorBase class for all JSON codec errors
JsonEncodeErrorJsonErrorRaised when encoding fails
JsonDecodeErrorJsonErrorRaised when decoding fails

The codec uses strict validation:

from tools.json_codec import encode, JsonEncodeError
try:
encode(float("nan"))
except JsonEncodeError as e:
print(e) # failed to encode float: failed to encode float: outliers must be a finite number
  • Encode/decode timing utilities via timed_encode() and timed_decode()
  • Streaming encoder for large payloads via encode_iter()
  • Built on stdlib json — no external dependencies

When the real M14 implementation lands:

  1. Replace tools/json_codec.py with axon_web.json module
  2. Update imports in consuming code
  3. Run full integration tests against HTTP server
  4. Benchmark against real-world payload distributions