urllib与json一起保存到变量

时间:2016-06-17 11:03:17

标签: python json python-2.7

请更正我的代码。我试图将这个网页的结果以json格式保存到python中的变量。

错误

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)

1 个答案:

答案 0 :(得分: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)

会做到这一点。