Chapter 5

JSON in Python

Complete guide to using JSON with Python

Python json Module

Python has a built-in json module that provides full JSON encoding and decoding capabilities.

💡 Import Module: import json

Serialization: Python Object → JSON

Use json.dumps() to convert Python objects to JSON string:

import json

# Python Dict
user = {
    "name": "John Doe",
    "age": 30,
    "skills": ["Python", "JavaScript"]
}

# Convert to JSON string
json_string = json.dumps(user)
print(json_string)
# Output: {"name": "John Doe", "age": 30, "skills": ["Python", "JavaScript"]}

# Formatted output (with indent)
json_formatted = json.dumps(user, indent=2, ensure_ascii=False)
print(json_formatted)

Common Parameters

  • • indent=n : Pretty print, n is indent spaces
  • • ensure_ascii=False : Preserve non-ASCII characters
  • • sort_keys=True : Sort by keys

Deserialization: JSON → Python Object

Use json.loads() to convert a JSON string to a Python object:

import json

# JSON String
json_string = '{"name": "Jane Smith", "age": 28, "isStudent": true}'

# Convert to Python Dictionary
user_obj = json.loads(json_string)
print(user_obj["name"])  # Output: Jane Smith
print(user_obj["age"])   # Output: 28

Type Mapping

JSON Type

  • object → dict
  • array → list
  • string → str

Python Type

  • number (int) → int
  • number (float) → float
  • true/false → True/False
  • null → None

File Operations

📖 Read JSON File

import json

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

💾 Write JSON File

import json

data = {"name": "John Doe", "age": 30}

with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

Practical Case: API Data Processing

Fetch and process JSON data from an API:

import json
import requests

# Fetch API Data
response = requests.get('https://api.example.com/users')
data = response.json()  # Automatically parse JSON

# Filter Data
young_users = [u for u in data['users'] if u['age'] < 30]

# Save to File
with open('young_users.json', 'w', encoding='utf-8') as f:
    json.dump(young_users, f, ensure_ascii=False, indent=2)