json.JSONEncoder Serializes Custom Types
Subclass json.JSONEncoder to serialize Decimal, date, and datetime values predictably, with a default fallback and safe round trips.
Code
import json
from datetime import date, datetime, timezone
from decimal import Decimal
class LedgerEncoder(json.JSONEncoder):
def default(self, value):
if isinstance(value, Decimal):
return {'amount': str(value), 'currency': 'USD'}
if isinstance(value, datetime):
return value.astimezone(timezone.utc).isoformat()
if isinstance(value, date):
return value.isoformat()
return super().default(value)
def main() -> None:
payload = {
'total': Decimal('19.99'),
'booked_at': datetime(2026, 11, 17, 9, 30, tzinfo=timezone.utc),
'due': date(2026, 12, 1),
}
text = json.dumps(payload, cls=LedgerEncoder, indent=2, sort_keys=True)
print(text)
# default= 回调是另一种写法:只处理未识别的类型
compact = json.dumps(payload, default=str)
print('fallback:', compact)
# 解码回字典后金额仍是字符串,避免浮点误差
restored = json.loads(text)
print('amount type:', type(restored['total']['amount']).__name__)
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
{
"booked_at": "2026-11-17T09:30:00+00:00",
"due": "2026-12-01",
"total": {
"amount": "19.99",
"currency": "USD"
}
}
fallback: {"total": "19.99", "booked_at": "2026-11-17 09:30:00+00:00", "due": "2026-12-01"}
amount type: strHow the snippet works
The working surface is the class LedgerEncoder and the functions default and main — everything else is wiring.
From decimal it pulls date, datetime, timezone, Decimal — the imports name exactly which library surface the snippet touches.
The return value is newly constructed — inputs are never handed back.
What to watch for
- Plan for an install step:
decimalis a real dependency, resolved by the package manager.
Using it
Signature: def default(self, value)
Output lines are prefixed (fallback:, amount type:), making each step’s effect easy to spot.
Key statements
return {'amount': str(value), 'currency': 'USD'}
return value.astimezone(timezone.utc).isoformat()
if isinstance(value, date):
return value.isoformat()
return super().default(value)
def main() -> None:
payload = {
'total': Decimal('19.99'),
'booked_at': datetime(2026, 11, 17, 9, 30, tzinfo=timezone.utc),
'due': date(2026, 12, 1),
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
FAQ
- Does `default` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What does json.JSONEncoder Serializes Custom Types print when run?
- The script runs standalone; its 2 labeled outputs include `fallback:`, `amount type:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.