This Python tutorial explains Custom JSON Encoding and Decoding. Follow the example, inspect the output, and practise an input change so you understand the behavior rather than simply copying the syntax.
What This Feature Does
Control JSON conversion for types outside the default JSON data model.
Pass a default callable to json.dumps() or implement JSONEncoder.default() for unsupported Python types. For decoding, object_hook can inspect dictionaries; encode explicit type markers only when the application owns the schema.
When to Use It
This technique belongs to JSON processing. It is useful when the input, operation and expected outcome are known. Start with a small controlled example before integrating it into a larger workflow.
Step-by-Step Python Example
Read the code once before running it. Notice which values are inputs, which function or method performs the work, and whether the result is returned or stored by changing an existing object.
import json
from decimal import Decimal
amount = {'price': Decimal('12.50')}
json_text = json.dumps(amount, default=str)
print(json_text)
print(type(json.loads(json_text)['price']).__name__)
Understanding the Code
- First, the imports make json, decimal available. They provide the filesystem, data or standard-library functions used later.
- Find the call json.dumps(amount, default=str). Its parameters determine the specific operation demonstrated in the title.
- Its purpose is to control json conversion for types outside the default json data model. Compare this description against the result printed by the program.
- The print() expressions display a checkable outcome. Print values and exception names are not substitutes for the program result itself.
Expected Output
{"price": "12.50"}
str
Each printed line corresponds to a separate observation in the program. Use the lines to distinguish returned data, changes to existing objects, and status checks.
Important Details and Edge Cases
Design an explicit JSON representation for one datetime and a decoder that validates it.
Decoding a valid file format does not automatically validate the meaning of its data. Confirm expected keys, types, permitted values and resource limits before using externally supplied content.
Practice: Try It Yourself
Never blindly reconstruct arbitrary Python classes from untrusted JSON type hints.
Begin by copying the example into a separate practice file. Change one input at a time, run it again, and describe why the result changed. If the exercise writes or deletes files, keep it inside a temporary test folder.
Official Python Documentation
For the complete reference, see the Python standard library documentation.
Common Beginner Mistakes
- Silently assuming Decimal survives a JSON round-trip as Decimal after encoding it to text.
- Design an explicit JSON representation for one datetime and a decoder that validates it.
- Decoding a valid file format does not automatically validate the meaning of its data. Confirm expected keys, types, permitted values and resource limits before using externally supplied content.
Key Takeaways
- Control JSON conversion for types outside the default JSON data model.
- Pass a default callable to json.dumps() or implement JSONEncoder.default() for unsupported Python types. For decoding, object_hook can inspect dictionaries; encode explicit type markers only when the application owns the schema.
- Avoid this common pitfall: Silently assuming Decimal survives a JSON round-trip as Decimal after encoding it to text.