目录:
json.loads():从 JSON 字符串到 Python 对象
import json
json_str = '{"name": "Alice", "age": 30, "is_student": false}'
python_dict = json.loads(json_str)
print(python_dict) # {'name': 'Alice', 'age': 30, 'is_student': False}
json.dumps():从 Python 对象到 JSON 字符串
import json
python_data = {
'name': 'Bob',
'age': 25,
'courses': ['Math', 'Physics'],
'active': True,
'score': None
}
json_str = json.dumps(python_data)
print(json_str) # {"name": "Bob", "age": 25, "courses": ["Math", "Physics"], "active": true, "score": null}
上面介绍的 loads() 和 dumps() 只是单纯的处理 Python 对象和 JSON 字符串转换。
如果和文件处理有关,可以使用 load() 和 dump()。
json.load():从文件读取 JSON 数据
import json
# 从文件读取JSON数据
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
json.dump():将数据写入 JSON 文件
import json
data = {
'username': 'admin',
'email': 'admin@example.com',
'preferences': {
'theme': 'dark',
'language': 'zh-CN'
}
}
# 将数据写入JSON文件
with open('user_config.json', 'w', encoding='utf-8') as file:
json.dump(data, file, indent=2)
默认情况下,json.dumps() 的 ensure_ascii 参数为 True,这会导致所有非 ASCII 字符(包括中文字符)被转义为 Unicode 转义序列:
import json
data = {'name': '张三', 'city': '北京'}
json_str_default = json.dumps(data)
print(json_str_default) # {"name": "\u5f20\u4e09", "city": "\u5317\u4ead"}
设置 ensure_ascii=False 保留中文字符
import json
data = {'name': '张三', 'city': '北京'}
json_str_chinese = json.dumps(data, ensure_ascii=False)
print(json_str_chinese) # {"name": "张三", "city": "北京"}
indent 参数是美化 JSON 输出的最基本也最有效的方法。通过设置缩进级别,可以让 JSON 数据具有清晰的结构层次:
import json
complex_data = {
'users': [
{'id': 1, 'name': 'Alice', 'roles': ['admin', 'editor']},
{'id': 2, 'name': 'Bob', 'roles': ['viewer']}
],
'settings': {
'theme': 'dark',
'notifications': True,
'language': 'en-US'
}
}
# 无缩进(默认)
compact_json = json.dumps(complex_data)
print("紧凑格式:", compact_json)
# 紧凑格式: {"users": [{"id": 1, "name": "Alice", "roles": ["admin", "editor"]}, {"id": 2, "name": "Bob", "roles": ["viewer"]}], "settings": {"theme": "dark", "notifications": true, "language": "en-US"}}
# 缩进2个空格
pretty_json = json.dumps(complex_data, indent=2)
print("\n美化格式(2空格缩进):")
print(pretty_json)
# 美化格式(2空格缩进):
# {
# "users": [
# {
# "id": 1,
# "name": "Alice",
# "roles": [
# "admin",
# "editor"
# ]
# },
# {
# "id": 2,
# "name": "Bob",
# "roles": [
# "viewer"
# ]
# }
# ],
# "settings": {
# "theme": "dark",
# "notifications": true,
# "language": "en-US"
# }
# }
# 缩进4个空格(更常见)
pretty_json_4 = json.dumps(complex_data, indent=4)
print("\n美化格式(4空格缩进):")
print(pretty_json_4)
# 美化格式(4空格缩进):
# {
# "users": [
# {
# "id": 1,
# "name": "Alice",
# "roles": [
# "admin",
# "editor"
# ]
# },
# {
# "id": 2,
# "name": "Bob",
# "roles": [
# "viewer"
# ]
# }
# ],
# "settings": {
# "theme": "dark",
# "notifications": true,
# "language": "en-US"
# }
# }
# 只添加换行符,不缩进
line_only = json.dumps(complex_data, indent=0)
print("\n只换行不缩进:")
print(line_only)
# 只换行不缩进:
# {
# "users": [
# {
# "id": 1,
# "name": "Alice",
# "roles": [
# "admin",
# "editor"
# ]
# },
# {
# "id": 2,
# "name": "Bob",
# "roles": [
# "viewer"
# ]
# }
# ],
# "settings": {
# "theme": "dark",
# "notifications": true,
# "language": "en-US"
# }
# }
当需要确保JSON输出的一致性时,可以使用 sort_keys=True 参数对字典键进行排序。
注意📢:只会对最外层的键进行排序,如果是嵌套字典,内层键是不会排序的。
import json
unordered_data = {'z': 1, 'a': 2, 'm': 3, 'b': 4}
# 不排序
unsorted_json = json.dumps(unordered_data, indent=2)
print("未排序:")
print(unsorted_json)
# 未排序:
# {
# "z": 1,
# "a": 2,
# "m": 3,
# "b": 4
# }
# 按键排序
sorted_json = json.dumps(unordered_data, indent=2, sort_keys=True)
print("\n按键排序:")
print(sorted_json)
# 按键排序:
# {
# "a": 2,
# "b": 4,
# "m": 3,
# "z": 1
# }
↶ 返回首页 ↶