Python JSON Handling Examples for API Automation
This article presents a comprehensive collection of Python code snippets demonstrating how to parse, construct, modify, query, and validate JSON data for common API automation tasks, covering conversion, file I/O, field extraction, merging, sorting, and token handling.
Example 1: Convert JSON string to Python dict
import json
json_str = '{"name": "张三", "age": 25, "city": "北京"}'
data_dict = json.loads(json_str)
print(data_dict) # Output: {'name': '张三', 'age': 25, 'city': '北京'}Example 2: Convert Python dict to JSON string
data_dict = {"username": "testuser", "password": "123456"}
json_output = json.dumps(data_dict, ensure_ascii=False)
print(json_output) # Output: {"username": "testuser", "password": "123456"}Example 3: Read JSON file content
import json
with open('testdata.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data) # Output the JSON content from the fileExample 4: Write data to a JSON file
import json
result_data = {"status": "success", "code": 200, "data": {"id": 100}}
with open('result.json', 'w', encoding='utf-8') as f:
json.dump(result_data, f, ensure_ascii=False, indent=4)
# result.json is created with formatted contentExample 5: Extract a nested field from JSON
json_data = {
"code": 200,
"data": {
"user": {
"id": 1,
"name": "李四"
}
}
}
user_name = json_data["data"]["user"]["name"]
print(user_name) # Output: 李四Example 6: Add a new field to JSON data
data = {"username": "admin", "token": "abc123"}
data["timestamp"] = "2025-04-30T09:14:00" # Add new field
print(data) # Output includes the timestampExample 7: Delete an unnecessary field from JSON
data = {"username": "testuser", "password": "123456", "age": 25}
del data["password"] # Remove sensitive field
print(data) # Output: {'username': 'testuser', 'age': 25}Example 8: Check if JSON contains a specific key
data = {"id": 100, "name": "用户A"}
if "name" in data:
print("包含 name 字段") # Output: 包含 name 字段Example 9: Iterate over all key‑value pairs in JSON
data = {"status": "ok", "count": 5, "items": [1, 2, 3]}
for key, value in data.items():
print(f"{key}: {value}")
# Outputs each pairExample 10: Merge two JSON objects
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print(merged) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}Example 11: Get a default value from nested JSON
data = {"user": {"name": "王五", "profile": {}}}
email = data.get("user", {}).get("email", "未填写")
print(email) # Output: 未填写Example 12: Filter a list of JSON objects by condition
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 17},
{"name": "Charlie", "age": 30}
]
adults = [u for u in users if u['age'] >= 18]
print(adults) # Output: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 30}]Example 13: Compare two JSON objects for equality
import json
res1 = {"code": 200, "data": {"name": "test"}}
res2 = {"code": 200, "data": {"name": "test"}}
if json.dumps(res1, sort_keys=True) == json.dumps(res2, sort_keys=True):
print("两个JSON相同") # Output: 两个JSON相同Example 14: Output JSON sorted by keys
data = {"b": 2, "a": 1, "c": 3}
sorted_json = json.dumps(data, sort_keys=True)
print(sorted_json) # Output: {"a": 1, "b": 2, "c": 3}Example 15: Parse API response JSON and verify status code
import requests, json
response = requests.get("https://api.example.com/status")
json_response = response.json()
if json_response.get("code") == 200:
print("接口调用成功")
else:
print("失败:", json_response.get("message"))Example 16: Extract token from login response and use it for subsequent requests
import requests
login_url = "https://api.example.com/login"
payload = {"username": "test", "password": "123456"}
response = requests.post(login_url, json=payload)
token = response.json().get("token")
headers = {"Authorization": f"Bearer {token}"}
user_info = requests.get("https://api.example.com/user", headers=headers)
print(user_info.json())Example 17: Use jsonpath to extract fields from complex JSON structures (third‑party library)
from jsonpath import jsonpath
data = {
"store": {
"book": [
{"title": "Book A", "price": 20},
{"title": "Book B", "price": 30}
]
}
}
titles = jsonpath(data, "$.store.book[*].title")
print(titles) # Output: ['Book A', 'Book B']
# Install with: pip install jsonpathExample 18: Convert Java‑style field names to Python‑style (key renaming)
def rename_keys(data):
return {k.replace("userName", "username"): v for k, v in data.items()}
json_data = {"userName": "Tom", "age": 25}
renamed = rename_keys(json_data)
print(renamed) # Output: {'username': 'Tom', 'age': 25}Example 19: Print JSON data as a formatted table
from tabulate import tabulate
data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 17}
]
table = tabulate(data, headers="keys", tablefmt="grid")
print(table)
# Install with: pip install tabulateExample 20: Mock an API response and wrap it in a function for unit testing
import json
def mock_api_response():
return json.dumps({
"code": 200,
"message": "Success",
"data": {"id": 1, "name": "Mock Data"}
})
response = mock_api_response()
print(response) # Output the mocked JSON stringThese Python JSON handling examples cover the most common operations needed in interface automation testing, including parsing/constructing, modifying/adding/removing fields, data extraction/assertion, logging/debugging, and mocking/encapsulating API responses. Mastering these techniques is essential for anyone involved in API automation.
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.