在 Python 中使用 JSON 和 JSON 键值

摘要:数据序列化是将数据转换为可以存储或传输的格式,然后在以后重建的过程。JSON(JavaScript 对象表示法)由于其可读性和易用性而成为最流行的序列化格式之一。

数据序列化是将数据转换为可以存储或传输的格式,然后在以后重建的过程。JSON(JavaScript 对象表示法)由于其可读性和易用性而成为最流行的序列化格式之一。

在 Python 中,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 保存为项目目录根目录中名为 data.json 的文件 — File:json_project/data.json

要将此 JSON 数据加载到 Python 中,请执行以下操作:

脚本:json_project/read_json.py

import json# Open and load the JSON filewith open("data.json", "r") as file: data = json.load(file)# Access elements from the loaded dataprint(f"Name: {data['name']}")print(f"Current Project: {data['projects']['current']}")

运行脚本:

python read_json.py

预期输出:

Name: AliceCurrent Project: Data Migration

要将 Python 数据结构另存为 JSON,请使用 json.dump。例如,让我们创建一个脚本来写入 JSON 数据:

脚本:json_project/write_json.py

import json# Data to be saved as JSONdata = { "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 filewith 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 数据,您可以通过链接键或索引来访问嵌套值。更新 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 filewith open("data.json", "r") as file: data = json.load(file)# Access nested dataapi_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 monthsTeam Size: 5

有时,JSON 数据以字符串形式出现,例如来自 API。您可以使用 json.loads 解析 JSON 字符串,使用 json.dumps 将 Python 对象转换为字符串:

脚本:json_project/json_strings.py

import json# JSON stringjson_string = '{"name": "Charlie", "age": 35, "skills": ["C++", "Rust"]}'# Convert string to Python objectpython_data = json.loads(json_string)print(f"Name: {python_data['name']}")# Convert Python object to JSON stringjson_output = json.dumps(python_data, indent=2)print(json_output)访问密钥

JSON 对象中的键可以像 Python 中的字典键一样访问。例如:

import json# Sample JSONjson_string = '''{ "name": "Alice", "age": 30, "skills": ["Python", "Data Analysis"], "projects": { "current": "Data Migration", "completed": ["API Development", "Web Scraping"] }}'''# Convert JSON string to Python dictionarydata = json.loads(json_string)# Access keysprint(data["name"]) # Output: Aliceprint(data["projects"]["current"]) # Output: Data Migration迭代 Key

要遍历 JSON 对象中的所有键,请执行以下操作:

# Looping through top-level keysfor key in data: print(f"Key: {key}, Value: {data[key]}")

输出:

Key: name, Value: AliceKey: age, Value: 30Key: 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 JSONkeys = data.keysprint(keys) # Output: dict_keys(['name', 'age', 'skills', 'projects'])

对于嵌套键,您需要单独访问它们:

nested_keys = data["projects"].keysprint(nested_keys) # Output: dict_keys(['current', 'completed'])添加或删除键添加 Key

删除密钥

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 keysall_keys = extract_keys(data)print(all_keys)

上述 JSON 的输出:

['name', 'age', 'skills', 'projects', 'projects.current', 'projects.completed']

来源:自由坦荡的湖泊AI一点号

相关推荐