Python and JSON: Complete Guide to json Module
Master JSON in Python with the json module. Learn to parse, generate, and manipulate JSON data with practical examples and best practices.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
The Python json Module
Python's built-in json module makes working with JSON data simple and efficient.
Parsing JSON
json.loads() - Parse JSON String
import json
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)
print(data['name']) # "Alice"
print(type(data)) # <class 'dict'>
json.load() - Read from File
import json
with open('data.json', 'r') as file:
data = json.load(file)
print(data)
Generating JSON
json.dumps() - Convert to JSON String
import json
data = {
"name": "Bob",
"age": 25,
"active": True
}
json_string = json.dumps(data)
print(json_string)
# {"name": "Bob", "age": 25, "active": true}
Pretty Printing
json_string = json.dumps(data, indent=2)
print(json_string)
# {
# "name": "Bob",
# "age": 25,
# "active": true
# }
json.dump() - Write to File
with open('output.json', 'w') as file:
json.dump(data, file, indent=2)
Type Mapping
| Python | JSON |
|--------|------|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True | true |
| False | false |
| None | null |
Common Options
Sort Keys
json.dumps(data, sort_keys=True)
Handle Non-Serializable Objects
from datetime import datetime
def json_serial(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
data = {"timestamp": datetime.now()}
json.dumps(data, default=json_serial)
Error Handling
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"Error: {e}")
print(f"Line {e.lineno}, Column {e.colno}")
Working with APIs
import requests
import json
response = requests.get('https://api.example.com/users')
data = response.json() # Automatically parses JSON
for user in data['users']:
print(user['name'])
Best Practices
with statement for file operationsJSONDecodeError exceptionsindent for readable outputConclusion
Python's json module is powerful and easy to use. Master json.loads(), json.dumps(), and file operations for all your JSON needs!
Related Articles
What is JSON? Complete Guide for Beginners 2026
Learn what JSON is, its syntax, data types, and use cases. A comprehensive beginner-friendly guide to understanding JavaScript Object Notation.
JavaScript JSON: Parse, Stringify, and Best Practices
Complete guide to JSON in JavaScript. Learn JSON.parse(), JSON.stringify(), error handling, and advanced techniques for web development.
JSON in Data Science: Python and Pandas Guide
Complete guide to JSON in data science workflows. Learn to process JSON with Python, Pandas, and integrate into ML pipelines.