JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据传输。Python 的 json
模块提供了序列化(将 Python 对象转换为 JSON 格式)和反序列化(将 JSON 格式转换回 Python 对象)的功能。
JSON 序列化(Python 对象 → JSON 字符串)
使用 json.dumps()
或 json.dump()
方法:
json.dumps(obj)
:将 Python 对象转换为 JSON 字符串。json.dump(obj, file)
:将 Python 对象写入文件。
示例 1:基本数据类型序列化
import json
# Python 字典 → JSON 对象
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"hobbies": ["reading", "coding"],
"address": {
"city": "Beijing",
"zipcode": "100000"
}
}
# 转换为 JSON 字符串
json_str = json.dumps(data, indent=2) # indent 参数美化格式
print(json_str)
# 输出:
# {
# "name": "Alice",
# "age": 30,
# "is_student": false,
# "hobbies": ["reading", "coding"],
# "address": {
# "city": "Beijing",
# "zipcode": "100000"
# }
# }
示例 2:写入文件
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # 直接写入文件
JSON 反序列化(JSON 字符串 → Python 对象)
使用 json.loads()
或 json.load()
方法:
json.loads(json_str)
:将 JSON 字符串解析为 Python 对象。json.load(file)
:从文件读取并解析 JSON。
示例 3:解析 JSON 字符串
json_str = '{"name": "Bob", "age": 25, "is_student": true}'
data = json.loads(json_str)
print(data) # 输出:{'name': 'Bob', 'age': 25, 'is_student': True}
print(type(data)) # 输出:<class 'dict'>
示例 4:从文件读取 JSON
with open("data.json", "r") as f:
data = json.load(f) # 从文件读取并解析
print(data)
JSON 与 Python 类型映射
JSON 类型 | Python 类型 |
---|---|
object | dict |
array | list |
string | str |
number | int , float |
true | True |
false | False |
null | None |