Python JSON Processing Guide

2026-01-15

The Built-in json Module

Python comes with a robust json library.

Basic Usage

import json

data = {"name": "Python", "fast": True}

# Serialize to String
json_str = json.dumps(data) 

# Parse from String
parsed = json.loads(json_str)

# Write to File
with open('data.json', 'w') as f:
    json.dump(data, f)

# Read from File
with open('data.json', 'r') as f:
    data = json.load(f)

Advanced Features

  1. Pretty Printing: json.dumps(data, indent=4)

  2. Sorting Keys: json.dumps(data, sort_keys=True) (Useful for consistent hashing)

  3. Custom Objects: You can't directly serialize a custom Class. You need a custom encoder.

    class User:
        def __init__(self, name):
            self.name = name
    
    def default(o):
        if isinstance(o, User):
            return {"name": o.name}
        raise TypeError
    
    json.dumps(User("Neo"), default=default)
    

Performance Alternatives

For high-performance applications, consider:

  • orjson: Extremely fast, Rust-based.
  • ujson: UltraJSON, historically popular for speed.