Python JSON
Learn how to convert Python data to JSON and back, and how to save structured data in JSON files.
Intermediate
JSON is a text-based data interchange format that is useful when structured data needs to be saved or exchanged. Python’s json module converts supported Python data structures to JSON and converts JSON back to Python values. File I/O gives you the file object; json gives the data conversion.
Convert Python data to JSON text
Use json.dumps() when you want the JSON representation as a Python string. This is serialization: Python data is converted into a JSON text representation.
import json
data = {"name": "Ada", "scores": [10, 20, 30], "active": True}
text = json.dumps(data)
print(text)
print(type(text).__name__)Convert JSON text back to Python data
Use json.loads() when the JSON data is already in a Python string. It deserializes the JSON text into Python values such as dict, list, str, int, float, bool, and None.
import json
text = '{"name": "Ada", "active": true, "score": 42}'
data = json.loads(text)
print(data["name"])
print(data["active"])
print(type(data).__name__)Save structured data to a JSON file
Use json.dump() to serialize Python data directly to a text file object. Use json.load() to read a JSON document from a text or binary file object and reconstruct the corresponding Python value. For JSON files, open text files with UTF-8 explicitly.
import json
from pathlib import Path
from tempfile import TemporaryDirectory
data = {"language": "Python", "version": 3}
with TemporaryDirectory() as folder:
path = Path(folder) / "data.json"
with open(path, "w", encoding="utf-8") as file:
json.dump(data, file)
with open(path, encoding="utf-8") as file:
restored = json.load(file)
print(restored)Make JSON easier to read
json.dumps() and json.dump() accept indent to add whitespace and line breaks for human-readable output. This changes formatting, not the underlying data represented by the JSON document.
import json
data = {"name": "Ada", "skills": ["Python", "Math"]}
print(json.dumps(data, indent=2))Know the Python-to-JSON mapping
The standard encoder maps common Python values to JSON values: dict to object, list and tuple to array, str to string, int and float to number, True and False to true and false, and None to null. Keep your data within these supported structures when you want straightforward JSON serialization.
import json
data = {
"text": "hello",
"items": [1, 2],
"enabled": True,
"missing": None,
}
print(json.dumps(data, indent=2))Handle invalid JSON
If JSON text is not a valid JSON document, json.loads() raises json.JSONDecodeError. Catch that exception when your program needs to report invalid input instead of stopping with an uncaught error.
import json
text = '{"name": "Ada"'
try:
data = json.loads(text)
except json.JSONDecodeError as error:
print(f"Invalid JSON: {error.msg}")Keep JSON and file I/O separate
File I/O answers “How do I access the file?” JSON answers “How do I represent structured data as JSON?” A typical workflow is: choose a Path, open the file with the correct text mode and UTF-8 encoding, then use json.dump() or json.load() on the file object. The json module does not replace pathlib or open().
Do not treat JSON as arbitrary Python serialization
JSON is designed for data interchange, not for preserving arbitrary Python objects. Custom classes and other values may need explicit conversion before they can be serialized. When loading untrusted JSON, still consider input size and resource limits; JSON decoding is data parsing, not a security boundary.
For this lesson, focus on dumps(), loads(), dump(), load(), common Python-to-JSON mappings, readable indentation, and JSONDecodeError. Custom encoders, decoder hooks, streaming details, and other serialization formats belong to later standard-library topics.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.