使用ijson的allow_comments=True报错:Python后端不支持注释
ijson
allow_comments=True 报错问题解决 ijson文档中记载了allow_comments=True选项,但使用该选项时会触发ValueError: Comments are not supported by the python backend错误,核心原因是该选项仅兼容非Python后端(如yajl2_c、yajl2),默认的纯Python后端不支持JSON注释解析。
测试代码(test.py)
import ijson # 正常调用(无注释选项) for o in ijson.items(open(0), 'item'): print(o) # 触发报错的调用(添加allow_comments=True) # for o in ijson.items(open(0), 'item', allow_comments=True): # print(o)
终端执行记录
$ python3 --version Python 3.10.9 # 原调用正常输出 $ python3 test.py <<< [1,2] 1 2 # 添加allow_comments=True后执行报错 $ python3 test.py <<< [1,2] Traceback (most recent call last): File "/Users/user/test.py", line 5, in <module> for o in ijson.items(open(0), 'item', allow_comments=True): File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 51, in coros2gen f = chain(events, *coro_pipeline) File "/usr/local/lib/python3.10/site-packages/ijson/utils.py", line 29, in chain f = coro_func(f, *coro_args, **coro_kwargs) File "/usr/local/lib/python3.10/site-packages/ijson/backends/python.py", line 284, in basic_parse_basecoro raise ValueError("Comments are not supported by the python backend") ValueError: Comments are not supported by the python backend
解决方法
要启用allow_comments=True功能,需切换到支持注释的后端,以yajl2为例:
- 安装包含yajl2后端的ijson版本:
pip install ijson[yajl2]
- 在代码中指定使用yajl2后端:
import ijson.backends.yajl2 as ijson for o in ijson.items(open(0), 'item', allow_comments=True): print(o)
内容的提问来源于stack exchange,提问作者peak
相关产品推荐
相关产品推荐

