2014-07-11 40 views
0

我有一個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。

+0

'ValueError:No JSON object can be decoding'意味着該文件包含無效的JSON。你可以用文件內容編輯你的文章嗎? – pswaminathan

+0

請將您文件的內容添加到您的問題中。 – timgeb

+0

錯誤表明您的文件在JSON對象被發現完成之前耗盡。 –

回答

5

你的文件中包含一個UTF-8 BOM character在開始。 UTF-8 不需要物料清單,但特別是微軟工具堅持要添加一個。

打開與utf-8-sig編碼,而不是文件:

>>> open('/tmp/json.test', 'wb').write(b'\xef\xbb\xbf{"data":\r\n {"mobileHelp":\r\n  {"value":\r\n   {\r\n   "ID1":{"children": [1,2,3,4,5]},\r\n   "ID2":{"children": []},\r\n   "ID3":{"children": [6,7,8,9,10]}\r\n   }\r\n  }\r\n }\r\n}') 
230 
>>> import json 
>>> with open('/tmp/json.test', encoding='utf8') as f: 
...  data = json.load(f) 
... 
Traceback (most recent call last): 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 367, 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 "<stdin>", line 2, in <module> 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 271, in load 
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 316, in loads 
    return _default_decoder.decode(s) 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 351, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 369, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 
>>> with open('/tmp/json.test', encoding='utf-8-sig') as f: 
...  data = json.load(f) 
... 
>>> data 
{'data': {'mobileHelp': {'value': {'ID2': {'children': []}, 'ID3': {'children': [6, 7, 8, 9, 10]}, 'ID1': {'children': [1, 2, 3, 4, 5]}}}}} 

注意,在Python 3.4起,你這裏得到更多有用的錯誤信息:

Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 268, in load 
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) 
    File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 314, in loads 
    raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)") 
ValueError: Unexpected UTF-8 BOM (decode using utf-8-sig) 
+0

完全釘着它,那編碼解決了它。謝謝!! – rodrigocf

2

不知道你的代碼看起來像第二個錯誤,但它看起來像你正在傳遞json.loads文件對象而不是字符串。嘗試:

with open('code test.txt', 'r', encoding=('UTF-8')) as f: 
    x = json.loads(f.read()) 

或不帶換行用:

with open('code test.txt', 'r', encoding=('UTF-8')) as f: 
    x = json.loads(f.read().replace('\n', '')) 
+2

'json.load'需要一個類文件對象,'json.loads'需要一個字符串。 – timgeb

+0

與此我仍然得到「沒有json對象可以被解碼」 – rodrigocf

+0

不知道爲什麼這個anwer有兩個upvotes,因爲它根本沒有解決問題; 'json.load()'(* no *'s')是一個非常有效的加載JSON文件的方法,*提供的文件數據可以被解碼並且是正確的*。 –

0

作爲另一種選擇,這將是多大更容易解決這個問題。

json.loads(open('test.txt').read().decode('utf-8-sig'))