2012-04-23 14 views
3

我有我使用wget得到它命名json.txt具有以下數據下面的JSON文件,閱讀使用JSON數據的文件與Python扔,我不能確定

{"id":99903727,"nickname":"TEST_MLA_OFF","registration_date":"2010-12-03T14:19:33.000-04:00","country_id":"AR","user_type":"normal","logo":null,"points":0,"site_id":"MLA","permalink":"http://perfil.mercadolibre.com.ar/TEST_MLA_OFF","seller_reputation":{"level_id":null,"power_seller_status":null,"transactions":{"period":"12 months","total":25,"completed":25,"canceled":0,"ratings":{"positive":0,"negative":0,"neutral":1}}},"status":{"site_status":"deactive"}} 

錯誤。我試圖加載JSON數據,使用下面的Python代碼蟒蛇,

json_data = json.load('json.txt') 
data = json.load(json_data) 
json_data.close() 

print data 

但引發以下錯誤,

Traceback (most recent call last): 
    File "json-example.py", line 28, in <module> 
    main() 
    File "json-example.py", line 21, in main 
    json_data = json.load('json.txt') 
    File "/opt/sage-4.6.2-linux-64bit-ubuntu_8.04.4_lts-x86_64-Linux/local/lib/python/json/__init__.py", line 264, in load 
    return loads(fp.read(), 
AttributeError: 'str' object has no attribute 'read' 

我無法找到谷歌搜索什麼是錯誤的原因。

此致敬禮。

回答

6

你需要給json.load文件流對象:

json_file = open('json.txt') 
data = json.load(json_file) 
json_file.close() 

print data 
+0

謝謝。就是這樣。最好的祝福。 – 2012-04-24 11:03:31

+0

我在包含'{「a」:1,「b」:2}'json對象的文件上嘗試了相同的操作,並且出現了'AttributeError:__exit__'錯誤。任何幫助都是有用的。 – chandresh 2017-03-08 11:18:09

14

甚至更​​好的做法是使用with聲明。

with open('json.txt', 'r') as json_file: 
    data = json.load(json_file) 

這將確保該文件被不 你擔心它正確關閉。