json.JSONEncoder Serializes Custom Types

Subclass json.JSONEncoder to serialize Decimal, date, and datetime values predictably, with a default fallback and safe round trips.

PythonData Integrity

Code

pythonsnippet
36 lines
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: str

How 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: decimal is 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

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:`.