How do I parse and generate JSON in Python?

· Category: Python Programming

Short answer

Use the json module to convert between Python objects and JSON strings. json.load() and json.loads() parse JSON into Python, while json.dump() and json.dumps() serialize Python objects into JSON.

Steps

  1. Import json.
  2. Parse JSON with json.loads(text) or json.load(file).
  3. Generate JSON with json.dumps(obj) or json.dump(obj, file).
import json

# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"])

# Generate JSON string
payload = {"status": "ok", "count": 42}
json_text = json.dumps(payload, indent=2)
print(json_text)

Tips

  • Use indent and sort_keys in json.dumps() to produce human-readable output.
  • Custom objects can be serialized by providing a default function.
  • Use object_hook or json.JSONDecoder subclasses for custom deserialization.
# Custom serialization
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def encode_point(obj):
    if isinstance(obj, Point):
        return {"x": obj.x, "y": obj.y}
    raise TypeError

p = Point(1, 2)
print(json.dumps(p, default=encode_point))

Common issues

  • JSON keys must be strings; Python converts non-string dict keys to strings.
  • Sets, tuples, and custom objects are not JSON-serializable by default.
  • json.load() expects a text file opened with the correct encoding, not binary mode.