json.loads Python3 中的 configParser 值错误

json.loads error with configParser value in Python3

我尝试在 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”return这个错误:

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() return 'string' 而不是“string”。如果有人对此有解决方案,那将非常有帮助。

JSON Specification 要求对字符串值使用双引号。 我试过 json.dumps(['foo', 'bar']) 并按预期输出双引号。

也许您可以将 config.ini 列表中的单引号更改为双引号,如下所示:

value2= ['test1', 'test2', 'test3']
f'''"value2" : {str(value2).replace("'", '"')},\n'''

的输出
value2= ["test1", "test2", "test3"]