A JSON round trip can preserve values while changing their Python types.
How It Works
json.dumps() creates JSON text and json.loads() reconstructs supported JSON values. Strings, numbers, null, arrays and objects have natural mappings, but tuples become lists and dictionary keys must be compatible with JSON object names. Datetimes, sets and custom classes need an explicit representation.
For data interchange, define a JSON-friendly schema rather than relying on incidental Python types.
Step-by-Step Example
import json
record = {"name": "Mira", "scores": (8, 9), "active": True}
encoded = json.dumps(record)
restored = json.loads(encoded)
print(restored)
print(type(restored["scores"]).__name__)
print(record == restored)
Understanding the Example
- The expression '{"name": "Mira", "scores": (8, 9), "active": True}' supplies the value stored as 'record'. This value is then used or checked by the later statements.
- The expression 'json.dumps(record)' supplies the value stored as 'encoded'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
{'name': 'Mira', 'scores': [8, 9], 'active': True}
list
False
Where This Fits in a Real Program
In a real import pipeline, parsing is only the first stage. Convert each field to the intended type, reject missing or unexpected values and report which record failed. Keep the original source file unchanged until the normalized data has passed validation and an export has been checked.
Practice: Try It Yourself
Replace the tuple with a list and verify what changes in the equality check.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming a tuple will remain a tuple after serializing to a JSON array.
- Assuming a custom class or datetime can be serialized without an encoder or conversion.
Key Takeaways
- A JSON round trip can preserve values while changing their Python types.
- json.dumps() creates JSON text and json.loads() reconstructs supported JSON values.
- For data interchange, define a JSON-friendly schema rather than relying on incidental Python types.