Comprehensive Guide to JSON Operations in Python
This tutorial presents a thorough collection of Python JSON handling techniques, covering basic conversion, file read/write, data manipulation, merging, pretty printing, nested structures, custom serialization, batch processing, backup creation, performance optimization with ujson, API interaction, aggregation, error handling, and processing of commented JSON files.
Basic Operations
Convert a Python dictionary to a JSON string, parse a JSON string back to a Python object, write a Python object to a JSON file, and read a JSON file into a Python object.
import json
# Python dictionary
data = {
'name': '张三',
'age': 30,
'city': '北京'
}
json_string = json.dumps(data, ensure_ascii=False)
print("Python对象转换为JSON字符串:")
print(json_string)
# JSON string
json_string = '{"name": "李四", "age": 35, "city": "上海"}'
# Parse JSON string
import json
data = json.loads(json_string)
print("JSON字符串解析为Python对象:")
print(data)
# Write to file
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
print("已将Python对象写入JSON文件")
# Read from file
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print("已从JSON文件读取Python对象:")
print(data)Data Manipulation
Modify, merge, add, or delete entries in JSON files.
# Modify JSON file data
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
data['age'] = 45
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
print("已修改JSON文件中的数据并保存")
# Merge two JSON files
with open('file1.json', 'r', encoding='utf-8') as f:
data1 = json.load(f)
with open('file2.json', 'r', encoding='utf-8') as f:
data2 = json.load(f)
combined_data = {**data1, **data2}
with open('combined.json', 'w', encoding='utf-8') as f:
json.dump(combined_data, f, ensure_ascii=False)
print("已合并两个JSON文件并保存")
# Add new key-value pair
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
data['职业'] = '工程师'
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
print("已添加新键值对并保存")
# Delete a key-value pair
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
del data['city']
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
print("已删除键值对并保存")Advanced Operations
Pretty‑print JSON, handle nested structures, and serialize complex objects with a custom default function.
# Pretty‑print JSON
data = {'name': '赵六', 'age': 28, 'city': '深圳'}
json_string = json.dumps(data, indent=4, ensure_ascii=False)
print("格式化输出JSON字符串:")
print(json_string)
# Nested JSON conversion
nested_data = {'name': '钱七', 'details': {'age': 32, 'city': '杭州'}}
json_string = json.dumps(nested_data, ensure_ascii=False)
print("嵌套JSON结构转换为JSON字符串:")
print(json_string)
# Parse nested JSON
json_string = '{"name": "孙八", "details": {"age": 36, "city": "南京"}}'
data = json.loads(json_string)
print("访问嵌套的数据:")
print(data['details']['city'])
# Custom default for complex objects
from datetime import datetime
complex_data = {'name': '周九', 'registered': datetime.now()}
def default(o):
if isinstance(o, datetime):
return o.isoformat()
json_string = json.dumps(complex_data, default=default, ensure_ascii=False)
print("处理复杂对象并转换为JSON字符串:")
print(json_string)File and Directory Operations
Batch‑process JSON files in a directory and create backup copies.
import os, json
json_files = [f for f in os.listdir() if f.endswith('.json')]
for file in json_files:
with open(file, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"已处理文件 {file}")
import shutil
shutil.copy('data.json', 'data_backup.json')
print("已创建备份文件")Performance Optimization
Use the ultra‑fast ujson library for serialization and deserialization.
import ujson
data = {'name': '吴十', 'age': 42, 'city': '成都'}
json_string = ujson.dumps(data, ensure_ascii=False)
data_back = ujson.loads(json_string)
print("使用ujson库提高性能:")
print(data_back)Special Uses
Fetch JSON data from a REST API and post JSON data to an API endpoint.
import requests
# GET request
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print("从API获取JSON数据成功:")
print(data)
else:
print("请求失败")
# POST request
payload = {'name': '郑十一', 'age': 38, 'city': '武汉'}
resp = requests.post('https://api.example.com/data', json=payload)
if resp.status_code == 200:
print("已将JSON数据写入API")
else:
print("请求失败")Data Analysis and Aggregation
Combine data from multiple JSON files into a single aggregated file.
import os, json
json_files = [f for f in os.listdir() if f.endswith('.json')]
aggregated_data = {}
for file in json_files:
with open(file, 'r', encoding='utf-8') as f:
data = json.load(f)
aggregated_data.update(data)
with open('aggregated_data.json', 'w', encoding='utf-8') as f:
json.dump(aggregated_data, f, ensure_ascii=False)
print("已聚合多个JSON文件的数据并保存")Error Handling
Catch and report JSON decoding errors gracefully.
import json
json_string = '{"name": "王十二", "age": "not a number", "city": "重庆"}'
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
else:
print("JSON解析成功:")
print(data)Special Format Handling
Read JSON files that contain comments using the jsoncomment library.
import jsoncomment
with open('data_with_comments.json', 'r', encoding='utf-8') as f:
data = jsoncomment.JsonComment().loads(f.read())
print("已读取带注释的JSON文件:")
print(data)These scripts cover a wide range of JSON processing tasks, from fundamental conversions to advanced handling, suitable for many real‑world Python applications.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.