在 Python 中使用 JSON 和 JSON 键值
数据序列化是将数据转换为可以存储或传输的格式,然后在以后重建的过程。JSON(JavaScript 对象表示法)由于其可读性和易用性而成为最流行的序列化格式之一。
在 Python 中,json 模块为处理 JSON 数据提供了强大的支持。
什么是JSON?
JSON 将数据表示为键值对。它支持简单的数据类型,如字符串、数字和布尔值,以及更复杂的结构,如数组和嵌套对象。典型的 JSON 文件可能如下所示:
{
"name": "Alice",
"age": 30,
"is_employee": true,
"skills": ["Python", "Data Analysis", "Machine Learning"],
"projects": {
"current": "Data Migration",
"completed": ["API Development", "Web Scraping"]
}
}
读取 JSON 文件
首先,将上述 JSON 保存为项目目录根目录中名为 data.json 的文件 — File:json_project/data.json
要将此 JSON 数据加载到 Python 中,请执行以下操作:
脚本:json_project/read_json.py
import json
# Open and load the JSON file
with open("data.json", "r") as file:
data = json.load(file)
# Access elements from the loaded data
print(f"Name: {data['name']}")
print(f"Current Project: {data['projects']['current']}")
运行脚本:
python read_json.py
预期输出:
Name: Alice
Current Project: Data Migration
编写 JSON 文件
要将 Python 数据结构另存为 JSON,请使用 json.dump。例如,让我们创建一个脚本来写入 JSON 数据:
脚本:json_project/write_json.py
import json
# Data to be saved as JSON
data = {
"name": "Bob",
"age": 25,
"is_employee": False,
"skills": ["Java", "Spring Boot", "DevOps"],
"projects": {
"current": "System Upgrade",
"completed": ["Automation", "Monitoring Setup"]
}
}
# Save data to a JSON file
with open("new_data.json", "w") as file:
json.dump(data, file, indent=4)
print("Data saved to new_data.json")
运行脚本:
python write_json.py
检查生成的 new_data.json 文件:
{
"name": "Bob",
"age": 25,
"is_employee": false,
"skills": [
"Java",
"Spring Boot",
"DevOps"
],
"projects": {
"current": "System Upgrade",
"completed": [
"Automation",
"Monitoring Setup"
]
}
}
使用嵌套 JSON
对于更复杂的 JSON 数据,您可以通过链接键或索引来访问嵌套值。更新 data.json 以包含更深的嵌套:
更新文件:json_project/data.json
{
"name": "Alice",
"age": 30,
"is_employee": true,
"skills": ["Python", "Data Analysis", "Machine Learning"],
"projects": {
"current": "Data Migration",
"completed": ["API Development", "Web Scraping"],
"details": {
"API Development": {
"duration": "3 months",
"team_size": 5
},
"Web Scraping": {
"duration": "1 month",
"team_size": 3
}
}
}
}
要访问嵌套详细信息:
脚本:json_project/nested_json.py
import json
# Load the updated JSON file
with open("data.json", "r") as file:
data = json.load(file)
# Access nested data
api_details = data["projects"]["details"]["API Development"]
print(f"API Development Duration: {api_details['duration']}")
print(f"Team Size: {api_details['team_size']}")
运行脚本:
python nested_json.py
预期输出:
API Development Duration: 3 months
Team Size: 5
将 JSON 字符串转换为 Python 对象
有时,JSON 数据以字符串形式出现,例如来自 API。您可以使用 json.loads 解析 JSON 字符串,使用 json.dumps 将 Python 对象转换为字符串:
脚本:json_project/json_strings.py
import json
# JSON string
json_string = '{"name": "Charlie", "age": 35, "skills": ["C++", "Rust"]}'
# Convert string to Python object
python_data = json.loads(json_string)
print(f"Name: {python_data['name']}")
# Convert Python object to JSON string
json_output = json.dumps(python_data, indent=2)
print(json_output)
访问密钥
JSON 对象中的键可以像 Python 中的字典键一样访问。例如:
import json
# Sample JSON
json_string = '''
{
"name": "Alice",
"age": 30,
"skills": ["Python", "Data Analysis"],
"projects": {
"current": "Data Migration",
"completed": ["API Development", "Web Scraping"]
}
}
'''
# Convert JSON string to Python dictionary
data = json.loads(json_string)
# Access keys
print(data["name"]) # Output: Alice
print(data["projects"]["current"]) # Output: Data Migration
迭代 Key
要遍历 JSON 对象中的所有键,请执行以下操作:
# Looping through top-level keys
for key in data:
print(f"Key: {key}, Value: {data[key]}")
输出:
Key: name, Value: Alice
Key: age, Value: 30
Key: skills, Value: ['Python', 'Data Analysis']
Key: projects, Value: {'current': 'Data Migration', 'completed': ['API Development', 'Web Scraping']}
检查键
在访问密钥之前,最好检查它是否存在以避免错误:
if "skills" in data:
print(f"Skills: {data['skills']}")
else:
print("Key 'skills' not found.")
列出所有键
您可以使用 .keys() 获取 JSON 对象中的所有键:
# Get all keys in the JSON
keys = data.keys()
print(keys) # Output: dict_keys(['name', 'age', 'skills', 'projects'])
对于嵌套键,您需要单独访问它们:
nested_keys = data["projects"].keys()
print(nested_keys) # Output: dict_keys(['current', 'completed'])
添加或删除键
您可以在 JSON 的 Python 字典表示形式中动态添加或删除键:
添加 Key
data["department"] = "Data Science"
print(data["department"]) # Output: Data Science
删除密钥
del data["age"]
print(data) # The 'age' key will no longer be in the data
实际用例:提取键
如果你有一个嵌套的 JSON 并且想要提取所有键(包括嵌套的键),请使用递归:
def extract_keys(obj, parent_key=""):
keys = []
for key, value in obj.items():
full_key = f"{parent_key}.{key}" if parent_key else key
keys.append(full_key)
if isinstance(value, dict):
keys.extend(extract_keys(value, full_key))
return keys
# Extract keys
all_keys = extract_keys(data)
print(all_keys)
上述 JSON 的输出:
['name', 'age', 'skills', 'projects', 'projects.current', 'projects.completed']