JSON Roundtrip Contract Guards
Round-trip data through json dumps and loads with sort_keys and parse hooks so key ordering and numeric types stay contract-stable.
Code
import json
from decimal import Decimal
def main() -> None:
payload = {
'id': 42,
'amount': Decimal('19.99'),
'tags': {'alpha', 'beta'},
'created': '2026-11-09T10:00:00+00:00',
}
def encode(obj):
if isinstance(obj, Decimal):
return {'__type': 'decimal', 'value': str(obj)}
if isinstance(obj, set):
return {'__type': 'set', 'values': sorted(obj)}
raise TypeError(f'cannot encode {type(obj).__name__}')
def decode(obj):
if obj.get('__type') == 'decimal':
return Decimal(obj['value'])
if obj.get('__type') == 'set':
return set(obj['values'])
return obj
blob = json.dumps(payload, default=encode, sort_keys=True)
print('wire:', blob)
restored = json.loads(blob, object_hook=decode)
print('id:', restored['id'], type(restored['amount']).__name__, restored['tags'])
# 契约守护:round-trip 后等价(Decimal 以字符串保精度)
assert restored['amount'] == payload['amount']
print('roundtrip ok')What the code does
Count the functions main, encode and decode as the entire surface area of JSON Roundtrip Contract Guards.
Reach for decimal and what you get is Decimal — that is the whole API contact area. A TypeError is raised unconditionally at its raise site — no input check sits in front of it.
A fresh value is allocated for the result; the arguments stay untouched.
Watch out for
- Dependency check:
decimal— not built-in, must be present in the project.
Using it
The main signature reads def main() -> None
Look for the wire:, id:, roundtrip ok prefixes when the file runs; they tie each line to its step.
The surface worth importing is main; the helpers around it are private to the snippet.
Key statements
return {'__type': 'decimal', 'value': str(obj)}
return {'__type': 'set', 'values': sorted(obj)}
def decode(obj):
if obj.get('__type') == 'decimal':
return Decimal(obj['value'])
if obj.get('__type') == 'set':
return set(obj['values'])
return obj
Interactive Tools for This Topic
FAQ
- Does `main` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Does the snippet validate its input?
- No. There is no input validation in the snippet — the `TypeError` is raised unconditionally at its site, with no check in front of it.
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `json`, `decimal`. The file defines `main`, `encode`, `decode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.