Json
在 Python 中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,使用内置的 json
模块可以方便地进行序列化(将 Python 对象转换为 JSON 格式)和反序列化(将 JSON 格式转换为 Python 对象)。
序列化(将 Python 对象转换为 JSON)
使用 json.dumps()
方法将 Python 对象转换为 JSON 字符串,或者使用 json.dump()
将其写入文件。
示例
python
import json
# Python 对象
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"]
}
# 序列化为 JSON 字符串
json_string = json.dumps(data)
print(json_string)
# 写入 JSON 文件
with open('data.json', 'w') as json_file:
json.dump(data, json_file)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
反序列化(将 JSON 转换为 Python 对象)
使用 json.loads()
方法将 JSON 字符串转换为 Python 对象,或者使用 json.load()
从文件中读取 JSON 数据。
示例
python
import json
# JSON 字符串
json_string = '{"name": "Alice", "age": 30, "is_student": false, "courses": ["Math", "Science"]}'
# 反序列化为 Python 对象
data = json.loads(json_string)
print(data)
# 从 JSON 文件读取并反序列化
with open('data.json', 'r') as json_file:
data_from_file = json.load(json_file)
print(data_from_file)
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
注意事项
- 数据类型:Python 的字典会被转换为 JSON 对象,列表会被转换为 JSON 数组,字符串、数字和布尔值会保持一致。
- 日期和时间:
json
模块不支持日期和时间对象,通常需要自定义序列化和反序列化方法。 - 编码:默认情况下,
json
模块使用 UTF-8 编码。
通过这些方法,你可以轻松地在 Python 中处理 JSON 数据。