Skip to main content Brad's PyNotes

JSON Module: Data Interchange Made Simple

TL;DR

The json module provides simple methods for converting between Python objects and JSON strings using loads() to parse JSON and dumps() to create JSON, essential for web APIs and data storage.

Interesting!

Python’s json module can handle custom object serialization with the default parameter in dumps() - you can make any Python object JSON-serializable with a simple function.

Basic JSON Operations

python code snippet start

import json

# Python to JSON
data = {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}
json_string = json.dumps(data)
print(json_string)  # {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}

# JSON to Python
parsed = json.loads(json_string)
print(parsed["name"])  # Alice

python code snippet end

File Operations

python code snippet start

# Save to file
with open('data.json', 'w') as file:
    json.dump(data, file, indent=2)

# Load from file
with open('data.json', 'r') as file:
    loaded_data = json.load(file)

python code snippet end

Custom Serialization

python code snippet start

from datetime import datetime

def json_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Object {obj} is not JSON serializable")

data = {"timestamp": datetime.now()}
json_string = json.dumps(data, default=json_serializer)

python code snippet end

The json module bridges Python objects and JSON format, enabling seamless data exchange across systems and languages.

For modern file handling when working with JSON files, combine json with pathlib's Path objects for cleaner, more readable code. JSON integrates seamlessly with urllib for web APIs and asyncio for async processing when building data-driven applications.

Reference: Python JSON Module Documentation