JSON encoder that handles datetime, Decimal, UUID, dataclasses, and sets without crashing.
Project description
philiprehberger-safe-json
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:
License
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file philiprehberger_safe_json-0.2.1.tar.gz.
File metadata
- Download URL: philiprehberger_safe_json-0.2.1.tar.gz
- Upload date:
- Size: 9.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
eebe4b54d1d3e6c3d0b29438a5ecd7aa879a9b8b70f49b34a73dbe0d3e98d7ef
|
|
| MD5 |
f3a319ef87dcf594242badfc8ad0f2b1
|
|
| BLAKE2b-256 |
06cfb49c6e3ae674699f59e170ebe50d770382a842fbe760e2219d06e6528395
|
File details
Details for the file philiprehberger_safe_json-0.2.1-py3-none-any.whl.
File metadata
- Download URL: philiprehberger_safe_json-0.2.1-py3-none-any.whl
- Upload date:
- Size: 6.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
742780a28c1a77f957503d4e9bda7bea880b034f26086d918674252b4a35c3e4
|
|
| MD5 |
06c246cec07351a73d08c68dd54b52b7
|
|
| BLAKE2b-256 |
268a23358b8a313b609e0d7f8149747b36556c2c2a6d1a1f7f6e0cb5dc403843
|