我有一個json字符串在一個txt文件中,我試圖讀取它來做一些其他的程序。它看起來像這樣:從txt文件讀取json的問題
with open('code test.txt', 'r', encoding=('UTF-8')) as f:
x = json.load(f)
我知道JSON是有效的,但我發現:
Traceback (most recent call last):
File "C:\Python33\lib\json\decoder.py", line 368, in raw_decode
obj, end = self.scan_once(s, idx)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
user_input()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
child_remover()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
x = json.load(f)
File "C:\Python33\lib\json\__init__.py", line 274, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Python33\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我用這個website檢查字符串是否是有效的。如果我使用.loads()
,我得到一個不同的錯誤:
Traceback (most recent call last):
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module>
user_input()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input
child_remover()
File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover
x = json.loads(f)
File "C:\Python33\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
本來JSON在我的腳本內嵌這樣的:
json_text="""json stuff here"""
,並沒有得到任何錯誤。有想法該怎麼解決這個嗎???
運行python 3.3.3以防萬一。
謝謝!
編輯:
只是一些隨機的(有效)的TXT JSON,我也得到了同樣的問題。這OS那些我試過之一:
{"data":
{"mobileHelp":
{"value":
{
"ID1":{"children": [1,2,3,4,5]},
"ID2":{"children": []},
"ID3":{"children": [6,7,8,9,10]}
}
}
}
}
有效期以及每個jsonlint.com。
'ValueError:No JSON object can be decoding'意味着該文件包含無效的JSON。你可以用文件內容編輯你的文章嗎? – pswaminathan
請將您文件的內容添加到您的問題中。 – timgeb
錯誤表明您的文件在JSON對象被發現完成之前耗盡。 –