Skip to main content

JSON encoder that handles datetime, Decimal, UUID, dataclasses, and sets without crashing.

Project description

philiprehberger-safe-json

Tests PyPI version GitHub release Last updated License Bug Reports Feature Requests Sponsor

JSON encoder that handles datetime, Decimal, UUID, dataclasses, and sets without crashing.

Installation

pip install philiprehberger-safe-json

Usage

from philiprehberger_safe_json import dumps, loads

data = {
    "created": datetime(2026, 3, 13, 12, 0, 0),
    "price": Decimal("19.99"),
    "id": UUID("12345678-1234-5678-1234-567812345678"),
    "tags": {"beta", "release"},
}

json_string = dumps(data)
parsed = loads(json_string)

Datetime and Date

from datetime import datetime, date
from philiprehberger_safe_json import dumps

dumps({"timestamp": datetime(2026, 1, 15, 9, 30, 0)})
# '{"timestamp": "2026-01-15T09:30:00"}'

dumps({"day": date(2026, 1, 15)})
# '{"day": "2026-01-15"}'

Decimal

from decimal import Decimal
from philiprehberger_safe_json import dumps

dumps({"price": Decimal("9.99")})
# '{"price": 9.99}'

dumps({"price": Decimal("9.99")}, decimal_as_string=True)
# '{"price": "9.99"}'

UUID

from uuid import UUID
from philiprehberger_safe_json import dumps

dumps({"id": UUID("abcdef01-2345-6789-abcd-ef0123456789")})
# '{"id": "abcdef01-2345-6789-abcd-ef0123456789"}'

Dataclasses

from dataclasses import dataclass
from philiprehberger_safe_json import dumps

@dataclass
class User:
    name: str
    age: int

dumps({"user": User(name="Alice", age=30)})
# '{"user": {"name": "Alice", "age": 30}}'

Sets and Frozensets

from philiprehberger_safe_json import dumps

dumps({"tags": {"c", "a", "b"}})
# '{"tags": ["a", "b", "c"]}'

Custom Type Encoders

from philiprehberger_safe_json import dumps, register_encoder

class Money:
    def __init__(self, amount: int, currency: str) -> None:
        self.amount = amount
        self.currency = currency

register_encoder(Money, lambda m: {"amount": m.amount, "currency": m.currency})

dumps({"payment": Money(1000, "USD")})
# '{"payment": {"amount": 1000, "currency": "USD"}}'

Circular Reference Detection

from philiprehberger_safe_json import dumps, CircularReferenceError

data = {"key": "value"}
data["self"] = data  # circular reference

dumps(data, detect_cycles=True)
# Raises CircularReferenceError

Safe Loads with Auto-Parsing

from philiprehberger_safe_json import safe_loads

result = safe_loads('{"created": "2026-03-13T14:30:00", "price": 19.99}')
# result["created"] -> datetime(2026, 3, 13, 14, 30, 0)
# result["price"] -> Decimal("19.99")

result = safe_loads('{"day": "2026-03-13"}')
# result["day"] -> date(2026, 3, 13)

Using SafeJsonEncoder Directly

import json
from philiprehberger_safe_json import SafeJsonEncoder

json.dumps({"key": some_value}, cls=SafeJsonEncoder)

API

Function / Class Description
SafeJsonEncoder json.JSONEncoder subclass that handles datetime, date, Decimal, UUID, dataclass, set, frozenset, bytes, Enum, and Path
SafeJsonEncoder.decimal_as_string Class attribute; when True, Decimal values serialize as strings instead of floats (default: False)
dumps(obj, *, decimal_as_string=False, detect_cycles=False, **kwargs) Serialize to JSON string using SafeJsonEncoder. Set detect_cycles=True to raise CircularReferenceError on circular refs
loads(s, **kwargs) Deserialize a JSON string. Pass-through to json.loads for API symmetry
safe_loads(s, *, parse_dates=True, parse_decimals=True, **kwargs) Deserialize with auto-parsing of ISO date strings to datetime/date and numeric values to Decimal
register_encoder(type_class, handler_fn) Register a custom encoder for a specific type without subclassing
clear_encoders() Remove all registered custom encoders
CircularReferenceError Exception raised when a circular reference is detected during serialization

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this package useful, consider giving it a star on GitHub — it helps motivate continued maintenance and development.

LinkedIn More packages

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_safe_json-0.2.0.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_safe_json-0.2.0-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_safe_json-0.2.0.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_safe_json-0.2.0.tar.gz
Algorithm Hash digest
SHA256 3e7dddab3d5712f7840bef8d69dfb47a7f38f8d889e322e325fe84181ac414b4
MD5 5589a66e7c04aa8fbdd1c991b1439f06
BLAKE2b-256 fd1cd0d4886cacf201f4c355a50428f77dff386dca7f3271ded1206be0083712

See more details on using hashes here.

File details

Details for the file philiprehberger_safe_json-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_safe_json-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f64a1f85d22fbd5ef9e7a1955c744dcfaa1ddd75427cdcb7bf89be4f52944684
MD5 5109dc41f57a5988d3dd44d0ac1d5294
BLAKE2b-256 8a95c9bbfb290bde566807da15ace3c543b4b897403541bb05907aa973c5db09

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page