圆月山庄资源网 Design By www.vgjia.com

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,json.loads,单引号

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com