JSON Data Processing

JSON (JavaScript Object Notation) is the most common data exchange format on the web. Almost all Web APIs return JSON data. Python's json module makes it easy to convert between Python objects and JSON strings.


1. Python Objects <-> JSON Strings

Example: Serializing to JSON String

PYTHON
import json

# Python dict -> JSON string (serialization)
data = {
    "name": "Zhang San",
    "age": 25,
    "is_student": False,
    "scores": [85, 92, 78],
    "address": None
}

json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
▶ Try it Yourself

Output:

JSON
{
  "name": "Zhang San",
  "age": 25,
  "is_student": false,
  "scores": [85, 92, 78],
  "address": null
}

Tip: ensure_ascii=False is important: Without this parameter, non-ASCII characters are escaped to Unicode codes. Use it to preserve original characters. indent=2 formats the output for readability. In production, use indent=None to compress into a single line, saving bandwidth.


2. JSON String -> Python Objects (Deserialization)

Example: Deserializing a JSON String

PYTHON
import json

json_str = '{"name": "Zhang San", "age": 25, "is_student": false, "scores": [85, 92, 78]}'

data = json.loads(json_str)
print(data)                             # {'name': 'Zhang San', 'age': 25, ...}
print(type(data))                       # <class 'dict'>
print(data["name"])                     # Zhang San
print(data["scores"][0])                # 85
▶ Try it Yourself

JSON Type to Python Type Mapping

JSON Python
string str
number int / float
boolean bool
null None
array list
object dict

3. JSON File I/O

Example: Reading and Writing JSON Files

PYTHON
import json

# Write to JSON file
data = {
    "students": [
        {"name": "Zhang San", "age": 20, "score": 85},
        {"name": "Li Si", "age": 21, "score": 92},
        {"name": "Wang Wu", "age": 19, "score": 78}
    ]
}

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

# Read JSON file
with open("students.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)

print(f"Number of students: {len(loaded['students'])}")
for s in loaded["students"]:
    print(f"  {s['name']}: {s['score']}")
▶ Try it Yourself

Example: Data Persistence (Difficulty: Star-Star)

PYTHON
import json
import os

DATA_FILE = "notes.json"

def load_notes():
    """Load notes from JSON file"""
    if not os.path.exists(DATA_FILE):
        return []
    with open(DATA_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_notes(notes):
    """Save notes to JSON file"""
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(notes, f, ensure_ascii=False, indent=2)

def add_note(title, content):
    """Add a note"""
    notes = load_notes()
    notes.append({"title": title, "content": content})
    save_notes(notes)
    print(f"Note added: {title}")

def list_notes():
    """List all notes"""
    notes = load_notes()
    if not notes:
        print("No notes yet")
        return
    for i, note in enumerate(notes, 1):
        print(f"{i}. {note['title']}")

add_note("Learning Python", "Learned the JSON module today")
add_note("Shopping List", "Buy milk, bread, eggs")
list_notes()
▶ Try it Yourself

4. Handling Complex Data Types

By default, the json module only supports basic types. Custom objects need manual conversion:

Example: Custom Serialization

PYTHON
import json
from datetime import datetime

def custom_serializer(obj):
    """Custom serialization — handles types like datetime"""
    if isinstance(obj, datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    raise TypeError(f"Cannot serialize {type(obj)}")

data = {
    "name": "Zhang San",
    "created_at": datetime.now(),
    "active": True
}

json_str = json.dumps(data, default=custom_serializer, ensure_ascii=False, indent=2)
print(json_str)
▶ Try it Yourself

Common Use Cases


FAQ

Q What's the difference between json.dumps() and json.dump()?
A dumps() returns a JSON string (s for string); dump() writes directly to a file object. Similarly, loads() parses from a string; load() reads from a file object. The 's' suffix indicates string.
Q What are the advantages of JSON over CSV?
A JSON supports nested structures (dicts within lists, lists within dicts), while CSV can only represent flat tables. JSON preserves data types automatically (numbers, booleans, null), while all CSV values are strings. JSON is more readable. The downside is that JSON files are usually larger than CSV.
Q What happens if ensure_ascii=False is not set?
A Chinese characters will be escaped into \uXXXX format. Program functionality is unaffected — json.loads() will restore them automatically. However, for human readability, escaped content is completely unreadable. Add ensure_ascii=False when you need to view JSON files manually.

Summary


Exercises

  1. Beginner (Difficulty: Star): Create a dictionary containing your name, age, and three hobbies (list). Use json.dumps() to output a formatted JSON string (preserve characters, indent 2).

  2. Intermediate (Difficulty: Star-Star): Write two functions: save_contacts(contacts) and load_contacts(). Save a contact list (list of dicts) to contacts.json and auto-load on program start. Each contact has a name, phone, and email.

  3. Advanced (Difficulty: Star-Star-Star): Implement a "simple data exporter" using JSON. Given a student score list students = [{"name": "Zhang San", "scores": {"Chinese": 85, "Math": 92}}], output as: 1) A formatted JSON file; 2) A compressed (no indent) JSON string; 3) A JSON string with sorted keys (sort_keys=True).

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏