我一直在尝试使用 JSON 来存储程序的设置。我似乎无法使用 Python 2.6 的 JSON 解码器来解码多行 JSON 字符串...
这是示例输入:
.settings file:
"""
{\
'user':'username',\
'password':'passwd',\
}\
"""
我已经为这个文件尝试了一些其他语法,我将在下面指定(以及它们导致的回溯)。
我读取文件的python代码是
import json
settings_text = open(".settings", "r").read()
settings = json.loads(settings_text)
这个的回溯是:
Traceback (most recent call last):
File "json_test.py", line 4, in <module>
print json.loads(text)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 322, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 2 - line 7 column 1 (char 2 - 41)
我假设“额外数据”是三重引号。
以下是我为 .settings 文件尝试过的其他语法及其各自的回溯:
"{\
'user':'username',\
'pass':'passwd'\
}"
Traceback (most recent call last):
File "json_test.py", line 4, in <module>
print json.loads(text)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 155, in JSONString
return scanstring(match.string, match.end(), encoding, strict)
ValueError: Invalid \escape: line 1 column 2 (char 2)
'{\
"user":"username",\
"pass":"passwd",\
}'
Traceback (most recent call last):
File "json_test.py", line 4, in <module>
print json.loads(text)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 338, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
如果我将所有设置放在一行中,它就可以正常解码。
最佳答案
去掉设置文件中的所有反斜杠和所有“Pythonic”引号。如果文件只是:
{
"user":"username",
"password":"passwd"
}
另请注意,JSON 字符串是用双引号引起来的,而不是单引号。请在此处查看 JSON 规范:
关于Python读取多行JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2913554/