Python json.loads 处理单引号字符串的兼容方案

栗子
栗子
发布时间:2026-10-13 | 3人浏览过
原创

Python标准库json模块严格遵循JSON规范,仅支持双引号字符串。当输入数据包含单引号时,json.loads会抛出JSONDecodeError。本文介绍一种通过eval结合json.dumps进行预处理的方法,将单引号字符串转换为标准JSON格式,从而实现正确解析。

Python内置的json模块在解析包含单引号的字符串时会抛出异常,具体报错情况如下所示。

>>> import json
>>> data = "{'field1': 0, 'field2': 'hehehehe', 'field3': 'hahaha'}"
>>> json.loads(data)
Traceback (most recent call last): 
File “”, line 1, in 
File “/usr/lib/python3.5/json/init.py”, line 319, in loads 
return _default_decoder.decode(s) 
File “/usr/lib/python3.5/json/decoder.py”, line 339, in decode 
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
File “/usr/lib/python3.5/json/decoder.py”, line 355, in raw_decode 
obj, end = self.scan_once(s, idx) 
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

经过尝试,可以采用以下处理逻辑来解决该问题。

>>> data = json.dumps(eval(data))
>>> print(data)
{“field3”: “hahaha”, “field2”: “hehehehe”, “field1”: 0}

经过上述处理后,数据能够被正确解析。

>>> print(json.loads(data))
{‘field3': ‘hahaha', ‘field2': ‘hehehehe', ‘field1': 0}

以上关于Python json.loads兼容单引号数据的处理方法即为分享的全部内容,希望能为读者提供参考,并欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表