Python JSON 解析:完整指南与实战 – wiki大全

My sincerest apologies. I’ve repeatedly failed to correctly identify my available tools. I cannot directly write files to the filesystem with the tools provided. I will output the requested article content as a text response instead of writing it to a file.

Here is the article:

Python JSON 解析:完整指南与实战

1. 引言:JSON 简介与 Python 的关系

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它易于人阅读和编写,也易于机器解析和生成。尽管其名称来源于 JavaScript,但 JSON 是一种独立于语言的数据格式,被广泛应用于各种编程语言和系统中,尤其是在 Web 服务和 API 数据传输中。

在 Python 中,处理 JSON 数据非常直观和高效,这得益于其内置的 json 模块。Python 对象和 JSON 结构之间有着天然的映射关系,使得数据的序列化(Python 对象转换为 JSON 格式)和反序列化(JSON 格式转换为 Python 对象)变得异常简单。

Python 对象与 JSON 类型的映射:

Python 类型 JSON 类型
dict object
list, tuple array
str string
int, float number
True true
False false
None null

2. Python 的 json 模块

Python 的 json 模块提供了处理 JSON 数据所需的所有功能。它主要包括四个核心函数:

  • json.loads(): 将 JSON 格式的字符串解析成 Python 对象。
  • json.dumps(): 将 Python 对象编码成 JSON 格式的字符串。
  • json.load(): 从 JSON 格式的文件中读取数据并解析成 Python 对象。
  • json.dump(): 将 Python 对象编码成 JSON 格式并写入文件。

导入模块

在使用之前,首先需要导入 json 模块:

python
import json

3. 解析 JSON 字符串 (json.loads())

json.loads() (load string 的缩写) 用于将一个包含 JSON 数据的字符串转换成 Python 对象(通常是字典或列表)。

基本示例:

“`python
import json

json_string = ‘{“name”: “Alice”, “age”: 30, “isStudent”: false, “courses”: [“Math”, “Science”]}’

将 JSON 字符串解析为 Python 字典

data = json.loads(json_string)

print(data)
print(type(data))
print(data[“name”])
print(data[“courses”][0])

输出:

{‘name’: ‘Alice’, ‘age’: 30, ‘isStudent’: False, ‘courses’: [‘Math’, ‘Science’]}

Alice

Math

“`

处理不同 JSON 数据类型:

“`python
import json

JSON 对象 (对应 Python 字典)

obj_json = ‘{“id”: 1, “product”: “Laptop”, “price”: 1200.50}’
obj_data = json.loads(obj_json)
print(f”JSON Object parsed: {obj_data}, type: {type(obj_data)}”)

JSON 数组 (对应 Python 列表)

arr_json = ‘[10, 20, “hello”, true, null]’
arr_data = json.loads(arr_json)
print(f”JSON Array parsed: {arr_data}, type: {type(arr_data)}”)

JSON 字符串

str_json = ‘”Hello JSON!”‘
str_data = json.loads(str_json)
print(f”JSON String parsed: {str_data}, type: {type(str_data)}”)

JSON 数字

num_json = ‘12345’
num_data = json.loads(num_json)
print(f”JSON Number parsed: {num_data}, type: {type(num_data)}”)

JSON 布尔值

bool_json = ‘true’
bool_data = json.loads(bool_json)
print(f”JSON Boolean parsed: {bool_data}, type: {type(bool_data)}”)

JSON null (对应 Python None)

null_json = ‘null’
null_data = json.loads(null_json)
print(f”JSON Null parsed: {null_data}, type: {type(null_data)}”)
“`

4. 解析 JSON 文件 (json.load())

json.load() (load file 的缩写) 用于从打开的文件对象中读取 JSON 数据并将其解析成 Python 对象。

示例:

首先,创建一个名为 config.json 的文件:

json
{
"database": {
"host": "localhost",
"port": 5432,
"user": "admin"
},
"settings": {
"debug_mode": true,
"max_connections": 100
},
"active_users": ["user1", "user2"]
}

然后,使用 json.load() 读取文件:

“`python
import json

假设 config.json 文件存在于当前目录

file_path = ‘config.json’

try:
with open(file_path, ‘r’, encoding=’utf-8′) as f:
config = json.load(f)

print(config)
print(f"Database host: {config['database']['host']}")
print(f"Debug mode: {config['settings']['debug_mode']}")

except FileNotFoundError:
print(f”Error: The file ‘{file_path}’ was not found.”)
except json.JSONDecodeError as e:
print(f”Error decoding JSON from ‘{file_path}’: {e}”)
“`

5. 序列化 Python 对象到 JSON 字符串 (json.dumps())

json.dumps() (dump string 的缩写) 用于将 Python 对象编码成 JSON 格式的字符串。

基本示例:

“`python
import json

python_dict = {
“name”: “Bob”,
“age”: 25,
“isEmployed”: True,
“skills”: [“Python”, “SQL”, “Git”],
“address”: None
}

json_output = json.dumps(python_dict)
print(json_output)
print(type(json_output))

输出:

{“name”: “Bob”, “age”: 25, “isEmployed”: true, “skills”: [“Python”, “SQL”, “Git”], “address”: null}

“`

美化输出 (pretty printing) indent 参数:

indent 参数可以指定缩进级别,使 JSON 输出更具可读性。

“`python
import json

python_dict = {
“name”: “Bob”,
“age”: 25,
“isEmployed”: True,
“skills”: [“Python”, “SQL”, “Git”],
“address”: None
}

缩进 4 个空格

pretty_json_output = json.dumps(python_dict, indent=4)
print(pretty_json_output)

输出:

{

“name”: “Bob”,

“age”: 25,

“isEmployed”: true,

“skills”: [

“Python”,

“SQL”,

“Git”

],

“address”: null

}

“`

排序键 sort_keys 参数:

sort_keys=True 会按照键的字母顺序对 JSON 对象进行排序。

“`python
import json

data = {“c”: 3, “a”: 1, “b”: 2}
sorted_json = json.dumps(data, sort_keys=True, indent=2)
print(sorted_json)

输出:

{

“a”: 1,

“b”: 2,

“c”: 3

}

“`

处理非 ASCII 字符 ensure_ascii 参数:

默认情况下,ensure_ascii=True 会将非 ASCII 字符转义。设置为 False 则会直接输出 Unicode 字符。

“`python
import json

data_chinese = {“city”: “北京”, “province”: “河北”}

默认行为:转义非 ASCII 字符

json_ascii = json.dumps(data_chinese)
print(f”ASCII encoded: {json_ascii}”)

不转义非 ASCII 字符

json_unicode = json.dumps(data_chinese, ensure_ascii=False)
print(f”Unicode: {json_unicode}”)

输出:

ASCII encoded: {“city”: “\u5317\u4eac”, “province”: “\u6cb3\u5317”}

Unicode: {“city”: “北京”, “province”: “河北”}

“`

6. 序列化 Python 对象到 JSON 文件 (json.dump())

json.dump() (dump file 的缩写) 用于将 Python 对象编码成 JSON 格式并写入一个文件对象。

示例:

“`python
import json

data_to_save = {
“report_id”: “R001”,
“date”: “2023-10-27”,
“metrics”: {
“sales”: 15000,
“customers”: 500,
“growth”: 0.12
},
“comments”: [“Generated automatically”, “Data up-to-date”]
}

output_file = ‘report.json’

try:
with open(output_file, ‘w’, encoding=’utf-8′) as f:
json.dump(data_to_save, f, indent=4, ensure_ascii=False) # indent 和 ensure_ascii 同样适用

print(f"Data successfully written to '{output_file}'")

except IOError as e:
print(f”Error writing to file ‘{output_file}’: {e}”)
“`

此时,report.json 文件内容将是:

json
{
"report_id": "R001",
"date": "2023-10-27",
"metrics": {
"sales": 15000,
"customers": 500,
"growth": 0.12
},
"comments": [
"Generated automatically",
"Data up-to-date"
]
}

7. 高级主题与错误处理

错误处理:json.JSONDecodeError

当尝试解析一个无效的 JSON 字符串时,json.loads()json.load() 会抛出 json.JSONDecodeError 异常。

“`python
import json

invalid_json_string = ‘{“name”: “Charlie”, “age”: 28,’ # 缺少闭合括号

try:
data = json.loads(invalid_json_string)
print(data)
except json.JSONDecodeError as e:
print(f”JSON 解析错误: {e}”)
print(f”错误位置: {e.pos}, 错误行: {e.lineno}, 错误列: {e.colno}”)

输出:

JSON 解析错误: Expecting property name or ‘}’ at bottom of string: line 1 column 26 (char 25)

错误位置: 25, 错误行: 1, 错误列: 26

“`

处理嵌套 JSON 结构

JSON 数据常常是多层嵌套的。通过连续的键访问或循环可以轻松处理。

“`python
import json

nested_json_string = “””
{
“store”: {
“book”: [
{
“category”: “fiction”,
“author”: “Evelyn Waugh”,
“title”: “Sword of Honour”,
“price”: 12.99
},
{
“category”: “fiction”,
“author”: “Herman Melville”,
“title”: “Moby Dick”,
“isbn”: “0-553-21311-3”,
“price”: 8.99
}
],
“bicycle”: {
“color”: “red”,
“price”: 19.95
}
},
“expensive”: 10
}
“””

data = json.loads(nested_json_string)

访问嵌套数据

book_category = data[“store”][“book”][0][“category”]
bicycle_color = data[“store”][“bicycle”][“color”]

print(f”First book category: {book_category}”)
print(f”Bicycle color: {bicycle_color}”)

遍历所有书籍

print(“\nAll Books:”)
for book in data[“store”][“book”]:
print(f” Title: {book[‘title’]}, Author: {book[‘author’]}, Price: {book[‘price’]}”)
“`

8. 实践应用

读取 API 响应

在 Web 开发中,JSON 是 API 响应的常用格式。

“`python
import requests
import json

假设这是一个返回 JSON 的 API

api_url = “https://jsonplaceholder.typicode.com/todos/1” # 这是一个公开的测试 API

try:
response = requests.get(api_url)
response.raise_for_status() # 检查 HTTP 请求是否成功

# 直接使用 .json() 方法将响应内容解析为 Python 对象
todo_item = response.json()

print(f"User ID: {todo_item['userId']}")
print(f"Title: {todo_item['title']}")
print(f"Completed: {todo_item['completed']}")

except requests.exceptions.RequestException as e:
print(f”API 请求失败: {e}”)
except json.JSONDecodeError as e:
print(f”API 响应解析失败: {e}”)
“`

配置文件的管理

JSON 文件常用于存储应用程序的配置,因为它们易于人类阅读和编辑。

“`python

假设 config.json 文件如第 4 节所示

def load_app_config(file_path):
try:
with open(file_path, ‘r’, encoding=’utf-8′) as f:
config = json.load(f)
return config
except FileNotFoundError:
print(f”Config file ‘{file_path}’ not found.”)
return None
except json.JSONDecodeError as e:
print(f”Error parsing config file ‘{file_path}’: {e}”)
return None

app_config = load_app_config(‘config.json’)

if app_config:
print(f”Loaded database port: {app_config[‘database’][‘port’]}”)
print(f”Loaded active users: {‘, ‘.join(app_config[‘active_users’])}”)
“`

9. 结论

Python 的 json 模块是处理 JSON 数据的强大而灵活的工具。无论是从字符串解析、从文件读取,还是将 Python 对象序列化为 JSON 字符串或写入文件,json 模块都提供了简单易用的函数。理解 loads()dumps()load()dump() 的用法,以及如何处理不同数据类型和错误,将使您在处理 JSON 数据时游刃有余。熟练掌握这些技能对于任何与 Web API 交互或需要存储和交换结构化数据的 Python 开发者来说都至关重要。

滚动至顶部