json.load / json.dump
Functions from the `json` module for reading (deserializing) and writing (serializing) JSON data directly to/from file-like objects.
json.load(fp)
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Functions from the `json` module for reading (deserializing) and writing (serializing) JSON data directly to/from file-like objects.
The `json` module provides a convenient way to work with JSON (JavaScript Object Notation) data, which is a lightweight data-interchange format. `json.dump(obj, fp)` serializes a Python object (`obj`) into a JSON formatted string and writes it to a file-like object (`fp`). This is the file-based counterpart to `json.dumps()`, which returns a JSON string. Key parameters for `json.dump()` include `indent` for pretty-printing (e.g., `indent=4`), and `eys=True` to output dictionaries with keys sorted alphabetically. `json.load(fp)` deserializes a JSON document from a file-like object (`fp`) and returns the corresponding Python object. This is the file-based counterpart to `json.loads()`, which parses a JSON string. Both `dump` and `load` handle the file I/O operations directly, making them ideal for persistent storage of Python data structures in a human-readable and interoperable format. When working with JSON files, it's crucial to open them in text mode (`'w'` for writing, `'r'` for reading) and use a `with` statement to ensure proper file handling and resource management. Error handling, such as catching `json.JSONDecodeError` for malformed JSON, is also a best practice.
Quick reference
Syntax
json.load(fp)
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)
Inputs
Parameters
See it in practice
Examples
Dumping a Python dictionary to a JSON file
import json
data = {
'name': 'Alice',
'age': 30,
'isStudent': False,
'courses': ['Math', 'Science']
}
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
# Verify content (optional, for demonstration)
with open('data.json', 'r') as f:
print(f.read()){ "name": "Alice", "age": 30, "isStudent": false, "courses": [ "Math", "Science" ] }
This example serializes a Python dictionary `data` into a JSON file named `data.json`. The `indent=4` argument ensures the output is pretty-printed with 4 spaces for readability.
Loading JSON data from a file into a Python dictionary
import json
# First, create a sample JSON file
with open('sample.json', 'w') as f:
f.write('{"city": "New York", "population": 8400000}')
# Now, load the data
with open('sample.json', 'r') as f:
loaded_data = json.load(f)
print(f"Loaded data: {loaded_data}")
print(f"Type of loaded data: {type(loaded_data)}")Loaded data: {'city': 'New York', 'population': 8400000} Type of loaded data: <class 'dict'>
This demonstrates `json.load()` reading a JSON formatted string from `sample.json` and converting it back into a Python dictionary. The `json` module automatically maps JSON types to their corresponding Python types.
Dumping with sorted keys and loading back
import json
data = {'b': 2, 'a': 1, 'c': 3}
with open('sorted_data.json', 'w') as f:
json.dump(data, f, indent=2, sort_keys=True)
with open('sorted_data.json', 'r') as f:
loaded_sorted_data = json.load(f)
print(f"Dumped and loaded data: {loaded_sorted_data}")Dumped and loaded data: {'a': 1, 'b': 2, 'c': 3}
The `eys=True` argument ensures that the keys in the JSON output are sorted alphabetically. When loaded back, Python dictionaries (from 3.7+) preserve insertion order, so the loaded dictionary will also have its keys sorted.
Debug faster
Common Errors
json.JSONDecodeError
Cause: Attempting to load a file that is not valid JSON, or contains syntax errors.
Fix: Ensure the input file contains well-formed JSON. Use online validators or carefully inspect the JSON structure. Implement `try-except json.JSONDecodeError` blocks for robust parsing.
import json
with open('malformed.json', 'w') as f:
f.write('{"key": "value", "another_key": }') # Missing value
# This will raise a json.JSONDecodeError
# with open('malformed.json', 'r') as f:
# json.load(f)Runtime support
Compatibility
Source: Python Docs
Common questions
Frequently Asked Questions
Functions from the `json` module for reading (deserializing) and writing (serializing) JSON data directly to/from file-like objects.
obj: The Python object to be serialized to JSON. fp: A file-like object (e.g., returned by `open()`) to which JSON data is written or from which it is read. indent: If provided, JSON output will be pretty-printed with the specified indent level. eys: If True, dictionary keys will be sorted in the output.
json.JSONDecodeError: Ensure the input file contains well-formed JSON. Use online validators or carefully inspect the JSON structure. Implement `try-except json.JSONDecodeError` blocks for robust parsing.