python处理json的核心操作是编码和解码。1. 解码(json -> python)使用json.loads()将字符串转为字典或列表,文件则用json.load()读取;2. 编码(python -> json)使用json.dumps()转为字符串,写入文件用json.dump()并可通过indent参数美化格式;3. 处理特殊字符需设置ensure_ascii=false并确保文件使用utf-8编码;4. 解析错误通过try...except捕获json.jsondecodeerror处理;5. 自定义编码解码行为可通过继承json.jsonencoder和json.jsondecoder实现;6. json schema用于数据验证,使用jsonschema库的validate函数校验数据结构是否符合预期。

JSON数据的处理,简单来说,就是把JSON字符串变成Python能理解的数据类型,反之亦然。

Python处理JSON主要依赖内置的json模块。核心操作就两个:编码(encode,也叫序列化,dumps)和解码(decode,也叫反序列化,loads)。

解码(JSON -> Python): 使用json.loads()函数。它能将JSON格式的字符串转换为Python字典、列表等数据结构。
立即学习“Python免费学习笔记(深入)”;
import json
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
python_dict = json.loads(json_string)
print(python_dict) # 输出: {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(type(python_dict)) # 输出: <class 'dict'>如果JSON数据来自文件,可以这样:

import json
with open('data.json', 'r') as f:
data = json.load(f) # 注意这里是 json.load 而不是 json.loads
print(data)编码(Python -> JSON): 使用json.dumps()函数。它将Python对象转换为JSON格式的字符串。
import json
python_dict = {"name": "Bob", "age": 25, "city": "Los Angeles"}
json_string = json.dumps(python_dict)
print(json_string) # 输出: {"name": "Bob", "age": 25, "city": "Los Angeles"}
print(type(json_string)) # 输出: <class 'str'>如果想把JSON数据写入文件:
import json
data = {"name": "Charlie", "age": 40, "city": "Chicago"}
with open('data.json', 'w') as f:
json.dump(data, f, indent=4) # indent参数让JSON更易读indent参数可以控制JSON的缩进,使其更易于阅读。 默认情况下,json.dumps() 输出的JSON字符串是没有缩进的,所有内容都挤在一行,可读性较差。设置 indent 为一个整数,可以指定缩进的空格数。
JSON字符串中可能包含特殊字符,比如中文、Unicode字符等。处理这些字符的关键在于编码方式。通常,建议使用UTF-8编码。
在json.dumps()中,可以使用ensure_ascii=False参数来允许非ASCII字符的出现。
import json
data = {"name": "张三", "city": "北京"}
json_string = json.dumps(data, ensure_ascii=False)
print(json_string) # 输出: {"name": "张三", "city": "北京"}
# 如果不加 ensure_ascii=False
json_string_ascii = json.dumps(data)
print(json_string_ascii) # 输出: {"name": "\u5f20\u4e09", "city": "\u5317\u4eac"}在读取JSON文件时,也要确保文件以UTF-8编码打开。
import json
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
print(data)JSON数据可能因为格式错误导致解析失败。为了程序的健壮性,需要进行错误处理。
import json
json_string = '{"name": "Eve", "age": 28, "city": "San Francisco",}' # 注意这里多了一个逗号
try:
python_dict = json.loads(json_string)
print(python_dict)
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")使用try...except块捕获json.JSONDecodeError异常,可以有效地处理JSON解析错误。 实际应用中,可以根据具体的错误信息进行更详细的处理,例如记录日志、通知管理员等。
json模块允许自定义编码和解码行为,以适应更复杂的数据结构。 可以通过继承json.JSONEncoder和json.JSONDecoder类来实现自定义的编码器和解码器。
例如,假设需要将Python的datetime对象编码为JSON字符串:
import json
from datetime import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data = {"time": datetime.now()}
json_string = json.dumps(data, cls=DateTimeEncoder)
print(json_string) # 输出类似于: {"time": "2023-10-27T10:30:00.000000"}在这个例子中,DateTimeEncoder类重写了default方法,用于处理datetime对象。 如果对象是datetime类型,就将其转换为ISO格式的字符串;否则,调用父类的default方法进行处理。
类似的,可以自定义解码器来将JSON字符串转换为Python的datetime对象。
JSON Schema是一种描述JSON数据结构的规范。它允许定义JSON数据的类型、格式、必需字段等约束条件。 使用JSON Schema可以有效地进行数据验证,确保JSON数据的有效性和完整性。
Python中可以使用jsonschema库来进行JSON Schema验证。
import json
from jsonschema import validate, ValidationError
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0},
"city": {"type": "string"}
},
"required": ["name", "age"]
}
data = {"name": "David", "age": 35, "city": "London"}
try:
validate(instance=data, schema=schema)
print("JSON数据验证通过")
except ValidationError as e:
print(f"JSON数据验证失败: {e}")
data_invalid = {"name": "David", "city": "London"} # 缺少 age 字段
try:
validate(instance=data_invalid, schema=schema)
print("JSON数据验证通过")
except ValidationError as e:
print(f"JSON数据验证失败: {e}") # 输出: JSON数据验证失败: 'age' is a required property在这个例子中,定义了一个JSON Schema,要求数据必须包含name和age字段,并且age必须是大于等于0的整数。 validate函数用于验证JSON数据是否符合Schema的定义。 如果验证失败,会抛出ValidationError异常。
以上就是怎样用Python处理JSON数据?编码解码最佳实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号