Python json解码器底层实现
2026/6/16 10:56:51 网站建设 项目流程

Python json模块解码器底层实现

json模块的JSONDecoder在CPython中用C实现(_json加速模块)。纯Python回退实现在json/decoder.py中。

JSONDecoder的扫描过程:

import json
from json.decoder import JSONDecoder

decoder = JSONDecoder()
result, idx = decoder.raw_decode('{"key": "value"} extra')
print(result) # {'key': 'value'}
print(idx) # 17(消耗的字符数)

raw_decode从指定位置开始解析,返回(解析结果,结束位置)。

decoder.scan_once是底层扫描函数。它通过一个大的switch语句处理不同的JSON token类型。

JSONEncoder的迭代编码:

encoder = json.JSONEncoder()
for chunk in encoder.iterencode({"key": "value"}):
print(chunk, end='')
# 逐步产生编码片段

iterencode用于流式编码大对象。

json.JSONEncoder的default方法处理不可序列化类型:

class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return {"__complex__": True, "real": obj.real, "imag": obj.imag}
if isinstance(obj, datetime.datetime):
return {"__datetime__": True, "value": obj.isoformat()}
if isinstance(obj, Decimal):
return str(obj)
return super().default(obj)

data = {"c": 3+4j, "d": Decimal("10.5")}
print(json.dumps(data, cls=CustomEncoder))

default在遇到不可序列化类型时被调用。如果default也无法处理,抛出TypeError。

object_hook和object_pairs_hook:

def as_complex(dct):
if '__complex__' in dct:
return complex(dct['real'], dct['imag'])
return dct

data = json.loads('{"val": {"__complex__": true, "real": 3, "imag": 4}}',
object_hook=as_complex)
print(data) # {'val': (3+4j)}

object_hook在每个JSON对象解码后调用。object_pairs_hook同样但接收有序键值对列表。

json.JSONEncoder的检查循环引用:

obj = {}
obj['self'] = obj
try:
json.dumps(obj)
except ValueError as e:
print(e) # Circular reference detected

JSONEncoder在编码时检测循环引用。通过_check_circular参数控制。

json.dumps的separators参数控制紧凑输出:

compact = json.dumps({"key": "value"}, separators=(',', ':'))
print(compact) # {"key":"value"}

默认separators=(', ', ': ')。compact版本去掉空格。

json.dump的ensure_ascii行为:

data = {"name": "中文"}
print(json.dumps(data)) # {"name": "中文"}
print(json.dumps(data, ensure_ascii=False)) # {"name": "中文"}

ensure_ascii=True时非ASCII字符被转义。False时输出原始Unicode。

sort_keys按键排序:

data = {"c": 3, "a": 1, "b": 2}
print(json.dumps(data, sort_keys=True)) # {"a": 1, "b": 2, "c": 3}

JSONDecoder的strict参数控制控制字符:

# strict=False允许控制字符(\x00-\x1f)
json.loads('{"key": "value\x00"}', strict=False)

json.tool命令行格式化:

# python -m json.tool input.json output.json

JSONDecodeError的详细信息:

try:
json.loads('{invalid}')
except json.JSONDecodeError as e:
print(f"Error at line {e.lineno}, col {e.colno}: {e.msg}")
print(f"Document: {e.doc}")
print(f"Position: {e.pos}")

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询