如何解决python.3中configParser值的json.loads错误
我尝试在python中使用JSON从config.ini文件中获取列表,但是当我在列表中使用“'”作为字符串值时,出现错误。令人惊讶的是,当我使用“”“时,我没有它。
Python代码:
from configparser import ConfigParser
import json
#set and read the config file
config = ConfigParser()
config.read('config.ini')
#get the list with : ""
thisworks = json.loads(config.get('VALUES','value1'))
#get the list with : ''
thisnotwork = json.loads(config.get('VALUES','value2'))
[VALUES]
value1 = ["tes1","test2","test3"]
value2 = ['tes1','test2','test3']
变量“ thisnotwork”返回此错误:
Traceback (most recent call last):
File "U:\Desktop\Nouveau dossier (2)\test.py",line 11,in <module>
thisnotwork = json.loads(config.get('VALUES','value2'))
File "C:\python37\lib\json\__init__.py",line 348,in loads
return _default_decoder.decode(s)
File "C:\python37\lib\json\decoder.py",line 337,in decode
obj,end = self.raw_decode(s,idx=_w(s,0).end())
File "C:\python37\lib\json\decoder.py",line 355,in raw_decode
raise JSONDecodeError("Expecting value",s,err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
[Finished in 0.258s]
这可能很烦人,因为json.dumps()返回“ string”而不是“ string” 。如果有人对此有解决方案,那将非常有帮助。
解决方法
JSON Specification要求双引号用于字符串值。
我尝试了json.dumps(['foo','bar'])
,它按预期输出了双引号。
也许您可以将config.ini
列表中的单引号更改为双引号,如下所示:
value2= ['test1','test2','test3']
f'''"value2" : {str(value2).replace("'",'"')},\n'''
输出为
value2= ["test1","test2","test3"]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。