我试图从此json bitcoin api
中提取数据存储在json文件中。首先我试过
import urllib, json
url = "http://api.coindesk.com/v1/bpi/currentprice.json"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
它起初工作但如果我再次运行它,我会收到此错误:
Traceback (most recent call last):
File "btc_api.py", line 4, in <module>
data = json.loads(response.read())
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
我必须定期运行代码以获取最新的货币并将其存储在数据库中。有人可以帮助我解决这个问题或任何想法如何更好地做到这一点?
答案 0 :(得分:2)
您可以将requests
与其提供的 json
方法一起使用:
import requests
url = "http://api.coindesk.com/v1/bpi/currentprice.json"
data = requests.get(url).json()
虽然如果您仍想使用 urllib
,请使用json.load
:
import urllib
import json
url = "http://api.coindesk.com/v1/bpi/currentprice.json"
response = urllib.urlopen(url)
data = json.load(response)