我一直在嘗試使用JSON來存儲程序的設置。我似乎無法得到的Python 2.6的JSON解碼器進行解碼的多線串JSON ...Python閱讀多行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
如果我把所有的設置在同一行,其解碼罰款。
這並不工作,當您創建的字符串解釋器,但從文件讀取時不起作用。 – 2010-05-26 14:01:50
@保羅:因爲你的文件內容不正確! – SilentGhost 2010-05-26 14:07:15