Last modified: May 28, 2026
Python JSON Module Guide
JSON stands for JavaScript Object Notation. It is a lightweight data format. Python's json module makes it easy to work with JSON data. You can convert Python objects to JSON strings. You can also parse JSON strings back to Python objects. This guide covers everything you need to know.
What is JSON?
JSON is a text-based data format. It uses key-value pairs. It is easy for humans to read and write. Machines can parse it quickly. Many APIs use JSON to send data. Web applications rely on JSON heavily. Python's json module handles all these tasks.
Installing the json Module
The json module comes built-in with Python. You do not need to install anything extra. Just import it in your script. It is part of the standard library. This makes it very convenient.
import json
Encoding Python Objects to JSON
Use json.dumps() to convert a Python object to a JSON string. This is called serialization. The function takes a Python object. It returns a string.
import json
# A Python dictionary
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Convert to JSON string
json_string = json.dumps(data)
print(json_string)
{"name": "Alice", "age": 30, "city": "New York"}
You can format the output. Use the indent parameter. This makes the JSON more readable.
import json
data = {"name": "Bob", "age": 25, "hobbies": ["reading", "gaming"]}
# Pretty print with indentation
json_string = json.dumps(data, indent=4)
print(json_string)
{
"name": "Bob",
"age": 25,
"hobbies": [
"reading",
"gaming"
]
}
Important: Not all Python types can be serialized. For example, datetime objects need special handling. The json module supports dict, list, tuple, string, int, float, True, False, and None.
Decoding JSON to Python Objects
Use json.loads() to parse a JSON string. This is called deserialization. The function returns a Python object.
import json
# A JSON string
json_string = '{"name": "Charlie", "age": 35, "city": "London"}'
# Parse to Python dictionary
data = json.loads(json_string)
print(data)
print(type(data))
{'name': 'Charlie', 'age': 35, 'city': 'London'}
<class 'dict'>
JSON arrays become Python lists. JSON objects become Python dictionaries. Strings remain strings. Numbers become int or float.
Working with JSON Files
Often you read JSON from a file. Use json.load() to read a file object. Use json.dump() to write to a file. These are similar to the string versions.
Writing to a file:
import json
data = {"name": "Diana", "age": 28, "skills": ["Python", "Data Science"]}
# Write to file
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Reading from a file:
import json
# Read from file
with open("data.json", "r") as file:
data = json.load(file)
print(data)
{'name': 'Diana', 'age': 28, 'skills': ['Python', 'Data Science']}
Handling Complex Data Types
The json module has limits. It cannot handle custom objects directly. You must define custom encoders and decoders. Use the default parameter in json.dumps(). This function handles unknown types.
import json
from datetime import datetime
def custom_encoder(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
data = {"event": "meeting", "time": datetime.now()}
json_string = json.dumps(data, default=custom_encoder)
print(json_string)
{"event": "meeting", "time": "2023-10-27T15:30:00.123456"}
Important: Always handle errors gracefully. Use try-except blocks when parsing user-provided JSON. Invalid JSON can raise a json.JSONDecodeError.
Sorting Keys and Ordering
You can sort keys in the output. Use the sort_keys parameter. This helps with consistency.
import json
data = {"c": 3, "a": 1, "b": 2}
json_string = json.dumps(data, sort_keys=True, indent=2)
print(json_string)
{
"a": 1,
"b": 2,
"c": 3
}
JSON and Python Type Mapping
Here is a simple mapping table. It shows how JSON types become Python types.
- JSON object → Python dict
- JSON array → Python list
- JSON string → Python str
- JSON number (int) → Python int
- JSON number (real) → Python float
- JSON true → True
- JSON false → False
- JSON null → None
Practical Example: API Response
Many web APIs return JSON. Here is a simulated example. It shows how to parse and use the data.
import json
# Simulated API response
api_response = '''
{
"status": "success",
"data": {
"users": [
{"id": 1, "name": "Eve"},
{"id": 2, "name": "Frank"}
]
}
}
'''
# Parse the response
parsed = json.loads(api_response)
# Access data
if parsed["status"] == "success":
for user in parsed["data"]["users"]:
print(f"User {user['id']}: {user['name']}")
User 1: Eve
User 2: Frank
Conclusion
The Python JSON module is powerful and easy to use. It helps you serialize and deserialize data. You can work with files, APIs, and complex types. Always validate your JSON input. Use indentation for readability. Handle errors with try-except blocks. Mastering JSON makes your Python code more versatile. Start using it in your projects today.