2016-06-17 32 views
0

請更正我的代碼。我試圖將這個網頁的結果以json格式保存到python中的一個變量中。urllib與json一起保存到變量


錯誤

Traceback (most recent call last): 
    File "C:/Users/Varen/Desktop/json_v1.py", line 5, in <module> 
    json.dump(link, f) 
    File "C:\Python27\lib\json\__init__.py", line 189, in dump 
    for chunk in iterable: 
    File "C:\Python27\lib\json\encoder.py", line 442, in _iterencode 
    o = _default(o) 
    File "C:\Python27\lib\json\encoder.py", line 184, in default 
    raise TypeError(repr(o) + " is not JSON serializable") 
TypeError: <addinfourl at 53244992 whose fp = <socket._fileobject object at 0x032B4AF0>> is not JSON serializable 

代碼

import urllib 
import json 
link = urllib.urlopen("http://www.saferproducts.gov/RestWebServices/Recall?RecallDateStart=2015-01-01&RecallDateEnd=2015-12-31&format=json") 
with open('link.json', 'w') as f: 
    json.dump(link, f) 
+0

在錯誤消息中:'not JSON serializable' - 檢查數據。 – henrikstroem

回答

0

你需要從像由urlopen()返回對象的文件讀取數據:

import urllib 
import json 

link = urllib.urlopen("http://www.saferproducts.gov/RestWebServices/Recall?RecallDateStart=2015-01-01&RecallDateEnd=2015-12-31&format=json") 
with open('link.json', 'w') as f: 
    json.dump(link.read(), f) 

會做的伎倆。

+0

它創建了一個空的json文件。 –

+0

你讀了多少次數據?如果您嘗試第二次讀取它,它將爲空,因爲數據已被第一次讀取消耗。我已經用完整的工作代碼更新了答案。如果將它粘貼到Python終端中,它應該工作。 – mhawke