Blog post
How to Work with JSON in Python: json Module Complete Guide
Complete guide to Python's json module — json.loads(), json.dumps(), custom encoders, datetime serialization, and reading/writing JSON files with examples.
Shashank Jain
Author


Article
Python's json Module
Python includes a built-in json module that handles JSON serialization and deserialization. No installation required.
Parse JSON from a String
import json
data = json.loads('{"name": "Alice", "age": 30}')
print(data['name']) # Alice
print(type(data)) # dictConvert Python to JSON String
import json
obj = {'name': 'Alice', 'age': 30, 'active': True}
json_str = json.dumps(obj, indent=2)
print(json_str)Read JSON from a File
import json
with open('data.json', 'r') as f:
data = json.load(f)
print(data)Write JSON to a File
import json
data = {'users': [{'id': 1, 'name': 'Alice'}]}
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)Handling Dates and Custom Types
from datetime import datetime
import json
# Serialize datetime
json.dumps({'created': datetime.now().isoformat()})
# Custom encoder
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json.dumps({'ts': datetime.now()}, cls=DateEncoder)json.dumps() Options Reference
| Parameter | Default | Purpose |
|---|---|---|
| indent | None | Pretty-print with N spaces |
| sort_keys | False | Sort object keys alphabetically |
| ensure_ascii | True | Escape non-ASCII chars |
| separators | (',', ': ') | Control separators for minifying |
Use the complete Python JSON guide at jsondecode.com for more examples.
Keep reading
Recent blogs

May 22, 2026
JSONPath Guide: Query JSON Data Like SQL (with Examples)
Learn JSONPath syntax to query JSON data — basic expressions, wildcards, filters, recursive descent, and array slices. Includes JavaScript and Python examples.

May 22, 2026
How to Convert JSON to TypeScript Interfaces Automatically
Learn how to convert JSON to TypeScript interfaces — manually, with tools, and with AI. Includes nested objects, arrays, optional fields, and Zod schema generation.

May 22, 2026
JSON Schema Validation: A Complete Guide with Examples
Learn JSON Schema validation from scratch — Draft 7 syntax, required fields, type constraints, pattern matching, array validation, and validation with AJV in JavaScript.