Python JSON serialize a Decimal object
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python Decimal is essential for precise values such as money, but the built-in json module does not serialize it by default. This mismatch causes runtime errors when API payloads include decimal fields. A good solution defines one consistent conversion policy and applies it at system boundaries.
Why Default json.dumps Fails
json.dumps supports only standard JSON-compatible Python types. Decimal is not one of them.
You must convert Decimal explicitly before encoding.
Quick Solution with default
Use default callback for one-off serialization.
Converting to string preserves exact decimal representation.
Reusable Encoder Class
For larger codebases, prefer a custom encoder class.
This keeps behavior consistent across services.
Choose String Versus Float Policy
Two common policies:
- Serialize as string for precision safety.
- Serialize as float for client convenience.
Float conversion may lose precision.
For finance, string policy is usually safer.
Parse Back to Decimal on Read
If JSON stores decimal as string, decode intentionally.
Round-trip behavior becomes explicit and testable.
Decode Numeric JSON to Decimal
If incoming JSON contains numeric tokens, parse_float helps.
This avoids binary float conversion during decode.
Apply Conversion at Boundaries Only
Keep Decimal in domain logic and convert only when crossing boundaries such as HTTP responses, message queues, or file export. Boundary-only conversion reduces accidental precision loss in internal calculations.
A clean architecture is:
- Domain layer uses
Decimal. - Serialization layer converts according to contract.
- Clients parse according to contract.
Define API Contract Clearly
If decimals are serialized as strings, document that in schema and examples.
Example payload:
Documenting scale and format avoids client-side ambiguity.
Nested Structure Handling
Real payloads often contain decimals inside nested dictionaries and lists. A centralized encoder handles this naturally because conversion is applied recursively during encoding.
This prevents partial fixes where top-level decimals are handled but nested ones still fail.
Testing Strategy
Add tests for nested objects, negative values, high precision values, and zero-scale values.
Contract-focused tests prevent silent behavior drift after refactors.
Common Pitfalls
- Converting
Decimalto float without precision review. - Using different conversion rules across endpoints.
- Forgetting nested decimal fields in lists and dictionaries.
- Omitting parse strategy on the consumer side.
- Not documenting decimal format in API contracts.
Summary
- Built-in JSON encoding does not handle
Decimalautomatically. - Use
defaultcallbacks or custom encoders consistently. - Prefer string encoding when exact precision matters.
- Decode with explicit decimal parsing rules.
- Keep conversion logic at system boundaries and enforce with tests.
Related reading
- Python json.loads shows ValueError Extra data
- Python k-means algorithm
- Python K-means fails to fit data when over 100 samples
- Python Kafka multiprocess vs thread
- Python Keras An layer output exactly the same thing as input
- Python Keras LSTM learning converges too fast on high loss
- Python kernel dies on Jupyter Notebook with tensorflow 2
- Python kernel dies when importing tensorflow 1.7
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.