JSON Handling
Parse, generate, and 验证 JSON 使用 JSON 模块, 自定义 encoders, and 错误 handling.
你将学到
- Parse JSON 字符串使用 JSON.加载()
- Generate JSON 使用 JSON.dumps() and 格式化
- 读取 and 编写 JSON files 使用加载() and dump()
- Handle 自定义类型使用默认 and object_hook
- Deal 使用 JSONDecodeError and encoding issues
概念讲解
The json Module
JSON (JavaScript Object Notation) is the most common data interchange format on the web. Python's built-in JSON module converts between JSON strings and Python objects:
| JSON | Python | |------|--------| | object | dict | | array | list | | string | str | | number (int) | int | | number (float) | float | | true/false | True/False | | null | None |
import json
# Parse a JSON string into Python objects
data = json.loads('{"name": "Ada", "age": 25, "active": true}')
print(data["name"]) # Ada
print(type(data)) # <class 'dict'>
# Convert Python objects to a JSON string
text = json.dumps({"name": "Ada", "age": 25})
print(text) # {"name": "Ada", "age": 25}
Parsing JSON: json.loads()
JSON.加载() (load string) parses a JSON string into Python objects:
import json
json_string = '''
{
"用户": [
{"name": "Ada", "age": 25},
{"name": "Bob", "age": 30}
],
"数量": 2,
"active": true
}
'''
data = json.loads(json_string)
print(data["用户"][0]["name"]) # Ada
print(data["数量"]) # 2
print(data["active"]) # True
# Access nested data
for user in data["用户"]:
print(f"{用户['name']} 是 {用户['age']}")
Generating JSON: json.dumps()
JSON.dumps() (dump string) converts Python objects to a JSON string:
import json
data = {
"name": "Ada",
"scores": [90, 85, 88],
"metadata": {"类": "CS101", "year": 2024}
}
# Basic — compact, no spaces
compact = json.dumps(data)
# Pretty-printed with indentation
pretty = json.dumps(data, indent=2)
print(pretty)
# {
# "name": "Ada",
# "scores": [90, 85, 88],
# "metadata": {
# "类": "CS101",
# "year": 2024
# }
# }
# Sort keys alphabetically
sorted_json = json.dumps(data, sort_keys=True, indent=2)
Useful dumps() parameters:
indent— number of spaces for indentation (pretty-print)sort_keys— sort dictionary keys alphabeticallyensure_ascii— set to False to keep Unicode characters instead of escaping themseparators— custom item and key separators
Reading and Writing Files
import json
# Write to a file
data = {"name": "Ada", "scores": [90, 85, 88]}
with open("数据.JSON", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# Read from a file
with open("数据.JSON", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["name"]) # Ada
Use JSON.dump() / JSON.加载() (without the 's') for files, and JSON.dumps() / JSON.加载() for strings. Always specify encoding="utf-8" when opening the file.
Custom Encoders
By default, JSON.dumps() only handles built-in types. For custom objects, provide a 默认 function:
import json
from datetime import datetime
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def encode_user(obj):
if isinstance(obj, User):
return {"name": obj.name, "age": obj.age}
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Cannot serialize {类型(obj)}")
user = User("Ada", 25)
print(json.dumps(user, default=encode_user, indent=2))
The 默认 function is called for any object the encoder does not know how to serialize. It should return a serializable representation or raise TypeError.
Custom Decoders
Use object_hook to customize how JSON objects are decoded:
import json
from datetime import datetime
def decode_dates(obj):
"""Convert ISO date 字符串后面到 datetime 对象."""
for key, value in obj.items():
if key.endswith("_at") and isinstance(value, str):
obj[key] = datetime.fromisoformat(value)
return obj
json_data = '{"created_at": "2024-01-15T14:30:00", "name": "Ada"}'
data = json.loads(json_data, object_hook=decode_dates)
print(type(data["created_at"])) # <class 'datetime.datetime'>
Error Handling
import json
try:
data = json.loads('{"无效": json,}')
except json.JSONDecodeError as e:
print(f"JSON parse 错误 at 行 {e.lineno}, 列 {e.colno}: {e.msg}")
# Common errors:
# - JSONDecodeError: malformed JSON
# - TypeError: object is not serializable
JSON.JSONDecodeError provides the line number, column, and error message — useful for debugging malformed JSON.
Practical: API Response Handling
import json
def save_response(response_text, filename):
"""Parse and pretty-保存 API JSON 响应."""
try:
data = json.loads(response_text)
except json.JSONDecodeError as e:
print(f"无效 JSON: {e}")
return False
with open(filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False, sort_keys=True)
return True
For production JSON handling, consider orjson (much faster) or pydantic (typed JSON with validation).
示例代码
import json
from datetime import datetime
# Parsing JSON string
json_string = '{"name": "Ada", "age": 25, "scores": [90, 85, 88], "active": true}'
data = json.loads(json_string)
print(f"Name: {data['name']}")
print(f"Scores: {data['scores']}")
print(f"Active: {data['active']}")
# Generating JSON
python_data = {
"project": "CoderNewbie",
"languages": ["Python", "JavaScript", "Rust"],
"version": 1.0,
"open_source": True,
"metadata": {"created": "2024-01-15", "author": None}
}
# Compact
compact = json.dumps(python_data)
print(f"Compact: {compact[:60]}...")
# Pretty-printed
pretty = json.dumps(python_data, indent=2, sort_keys=True)
print("Pretty:")
print(pretty)
# Custom encoder for datetime
def custom_encoder(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Cannot serialize {type(obj)}")
event = {"name": "launch", "timestamp": datetime(2024, 1, 15, 10, 0, 0)}
event_json = json.dumps(event, default=custom_encoder, indent=2)
print(f"Event with datetime: {event_json}")
# Error handling
try:
bad = json.loads('{"broken": json}')
except json.JSONDecodeError as e:
print(f"Parse error: {e.msg} at line {e.lineno}")
# Round-trip: Python → JSON → Python
original = {"a": 1, "b": [2, 3], "c": {"d": True}}
roundtrip = json.loads(json.dumps(original))
print(f"Round-trip equal: {original == roundtrip}")
# Writing to a string with ensure_ascii=False for Unicode
unicode_data = {"greeting": "Hello, 世界!"}
print(json.dumps(unicode_data, ensure_ascii=False))
Shows parsing 使用加载(), generating 使用 dumps() (compact and pretty), 自定义 encoder for datetime, 错误 handling for malformed JSON, round-trip verification, and Unicode handling 使用 ensure_ascii=假.
动手试一试
- JSON Formatter
练习格式化 and 验证 JSON — 核心的 JSON.dumps().
- CSV 到 JSON
Converting CSV 到 JSON uses JSON.dumps() — see transformation live.
常见错误
错误写法
Using JSON.dump() (for files) 当你 需要字符串, or JSON.dumps() 当编写到 file
正确做法
JSON.dumps() 返回字符串 ('s' stands for 字符串). JSON.dump() 编写到 file 对象. Use dumps/加载 for 字符串, dump/加载 for files. Mixing 它们上 是常见错误 — remember 's' 平均值字符串.
错误写法
Forgetting ensure_ascii=假 and 获取 escaped Unicode 如 \u4e16 相反的 实际 characters
正确做法
通过默认, JSON.dumps() escapes 非-ASCII characters. 通过 ensure_ascii=假到 keep Unicode characters as-是 in 输出. 总是 pair 这个使用 encoding='utf-8' 当编写到 file.
相关资源
相关速查表
- Python Cheatsheet
JSON 模块函数, 自定义 encoders, and 错误 handling.
练习 JSON Handling
2 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。