Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/python/cpython/llms.txt

Use this file to discover all available pages before exploring further.

The json module provides functions for encoding and decoding JSON data.

Module Import

import json

Encoding (Python to JSON)

dumps() - Serialize to String

import json

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'NYC',
    'hobbies': ['reading', 'coding']
}

# Convert to JSON string
json_string = json.dumps(data)
print(json_string)
# '{"name": "Alice", "age": 30, "city": "NYC", "hobbies": ["reading", "coding"]}'

# Pretty print
json_string = json.dumps(data, indent=2)
print(json_string)
# {
#   "name": "Alice",
#   "age": 30,
#   ...
# }

dump() - Write to File

import json

data = {'name': 'Alice', 'age': 30}

with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

Decoding (JSON to Python)

loads() - Parse String

import json

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

load() - Read from File

import json

with open('data.json', 'r') as f:
    data = json.load(f)
print(data)

Type Mapping

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

Options

import json

data = {'name': 'Alice', 'items': [1, 2, 3]}

# Compact output
json.dumps(data, separators=(',', ':'))
# '{"name":"Alice","items":[1,2,3]}'

# Sort keys
json.dumps(data, sort_keys=True)

# Handle non-serializable objects
import datetime

def serialize_datetime(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

data = {'timestamp': datetime.datetime.now()}
json.dumps(data, default=serialize_datetime)

Practical Examples

Config File

import json

config = {
    'database': {
        'host': 'localhost',
        'port': 5432,
        'name': 'mydb'
    },
    'debug': True
}

# Save config
with open('config.json', 'w') as f:
    json.dump(config, f, indent=2)

# Load config
with open('config.json', 'r') as f:
    config = json.load(f)

API Response

import json

# Parse API response
response_text = '{"status": "success", "data": {"id": 1, "name": "Item"}}'
response = json.loads(response_text)

if response['status'] == 'success':
    print(f"Item: {response['data']['name']}")

pickle

Python object serialization

csv

CSV file handling