JSON Encoder

0.4.4 · maintenance · verified Thu Apr 16

json-encoder is a Python library (version 0.4.4) designed to simplify JSON serialization by using the `singledispatch` pattern, eliminating the need for extensive `json.dumps(data, cls=MyJSONEncoder)` calls. It offers default serialization for common types like `time`, `date`, `datetime`, `UUID`, and `Decimal`, and can parse JSON float numbers into `Decimal` objects to mitigate Python float precision issues. The library is designed to be largely independent of specific underlying JSON implementations (e.g., `json`, `simplejson`, `ujson`), allowing users to choose their preferred backend.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `json-encoder` for basic data types that are typically not JSON-serializable (like `datetime`, `Decimal`, `UUID`), and how to register a custom serialization function for your own classes using the `singledispatch` decorator. It also shows how to optionally switch the underlying JSON library.

from datetime import datetime, date
from decimal import Decimal
from fractions import Fraction
from uuid import UUID

from json_encoder import json
from json_encoder import use_json_library
from json_encoder.encoder import json_encoder

# Optionally configure a specific JSON backend (e.g., ujson if installed)
try:
    import ujson
    use_json_library(ujson)
    print("Using ujson backend")
except ImportError:
    print("ujson not found, using default json backend")

# 1. Basic usage with built-in enhanced types
data = {
    'now': datetime.now(),
    'today': date.today(),
    'money': Decimal('123.45'),
    'id': UUID('12345678-1234-5678-1234-567812345678'),
    'value': 1.23 # will be handled as Decimal due to float parsing
}

encoded_data = json.dumps(data, indent=2)
print("\nEncoded data with default handlers:")
print(encoded_data)

# 2. Registering a custom type handler using singledispatch
class MyCustomType:
    def __init__(self, name, value):
        self.name = name
        self.value = value

@json_encoder.register(MyCustomType)
def encode_my_custom_type(obj: MyCustomType):
    return {
        'custom_name': obj.name,
        'custom_value': obj.value,
        'type_info': 'MyCustomType serialized'
    }

custom_data = {'item': MyCustomType('test', 100)}
encoded_custom_data = json.dumps(custom_data, indent=2)
print("\nEncoded data with custom type handler:")
print(encoded_custom_data)

# 3. Example for Fraction (from PyPI docs)
@json_encoder.register(Fraction)
def encode_fraction(obj: Fraction):
    return float(obj)

fraction_data = {'ratio': Fraction(1, 3)}
encoded_fraction = json.dumps(fraction_data, indent=2)
print("\nEncoded Fraction:")
print(encoded_fraction)

view raw JSON →