Skip to main content

philiprehberger-safe-json

Tests PyPI version Last updated

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 project useful:

⭐ Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

Release files for philiprehberger-safe-json 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for philiprehberger-safe-json 0.2.1
File Size Uploaded
philiprehberger_safe_json-0.2.1.tar.gz 9.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for philiprehberger-safe-json 0.2.1
File Interpreter ABI Platform
philiprehberger_safe_json-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 16.1 kB

Release files / philiprehberger_safe_json-0.2.1.tar.gz

Download URL philiprehberger_safe_json-0.2.1.tar.gz
Size 9.6 kB
Tags Source
SHA-256 checksum
How to use checksums
eebe4b54d1d3e6c3d0b29438a5ecd7aa879a9b8b70f49b34a73dbe0d3e98d7ef
BLAKE2b-256 checksum
How to use checksums
06cfb49c6e3ae674699f59e170ebe50d770382a842fbe760e2219d06e6528395
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / philiprehberger_safe_json-0.2.1-py3-none-any.whl

Download URL philiprehberger_safe_json-0.2.1-py3-none-any.whl
Size 6.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
742780a28c1a77f957503d4e9bda7bea880b034f26086d918674252b4a35c3e4
BLAKE2b-256 checksum
How to use checksums
268a23358b8a313b609e0d7f8149747b36556c2c2a6d1a1f7f6e0cb5dc403843
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files

0.2.0

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page