【发布时间】:2020-11-10 14:09:40
【问题描述】:
我尝试在 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'))
config.ini 文件:
[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() 返回“字符串”而不是“字符串”。如果有人对此有解决方案,那将非常有帮助。
【问题讨论】:
-
我希望在您的文件中存储
json可以正常工作。那么,以什么方式:json.dumps() returns 'string' and not "string"?当我这样做时:value2 = ['tes1', 'test2', 'test3']; json.dumps(value2)我得到:["tes1", "test2", "test3"]。我希望你在某个时候做到了:config['VALUES']['value2'] = str(value2). -
config.ini文件有什么不一致的?只有双引号。 -
@quamrana 你说得对,我更新了这个
-
没有办法解决这个问题。如果您想在
ini文件中使用json数据,那么最好的方法是在写入时使用json.dump()为您生成字符串,那么您已经拥有的json.loads()将始终有效。可以选择使用try: except:丢弃无效数据。 -
@quamrana 谢谢,你解决了我的问题。它是更复杂脚本的简单版本。但我的问题是因为 i .dumps() 字典的列表,这就是为什么引用没有在列表中设置正确的方式。现在好了。
标签: python json python-3.x configparser