所以我试图使用请求从vaultofsatoshi.com API获取dogecoin(加密货币,对于那些不熟悉的人)的日期和平均价格,每当我尝试运行以下代码时我都会收到错误
import requests
contents = requests.get("https://api.vaultofsatoshi.com/public/ticker?order_currency=DOGE&payment_currency=USD")
print contents.json()[{"data":{"date","average_price"}}]
这是错误:
Traceback (most recent call last):
File "filename", line 5 in <module>
print contents.json()[{"data":{"date","average_price"}}]
TypeError: unhashable type: 'dict'
澄清我是API和请求模块的新手,所以我对语法不是很熟悉,非常感谢任何帮助。
编辑:使用URL修复拼写错误并供参考,这是它将返回的字典
{"status":"success","data":{"date":1392701294,"opening_price":
{"precision":5,"value":"0.00150000","value_int":150},"closing_price":
{"precision":5,"value":"0.00153000","value_int":153},"units_traded":
{"precision":8,"value":"15941676.33311552","value_int":1594167633311552},"max_price":
{"precision":5,"value":"0.00154900","value_int":154},"min_price":
{"precision":5,"value":"0.00141000","value_int":141},"average_price":
{"precision":5,"value":"0.00148","value_int":148},"volume_1day":
{"precision":8,"value":"15941676.33311552","value_int":1594167633311552},"volume_7day":
{"precision":8,"value":"115024501.70386628","value_int":11502450170386628}}}
答案 0 :(得分:0)
请求响应.json()
方法返回其他词典的字典。
首先让我们看一下你要回来的JSON对象。我们将使用pprint
来打印结果,以便我们了解它们的结构。
import requests
import pprint
contents = requests.get("https://api.vaultofsatoshi.com/publi/ticker?order_currency=DOGE&payment_currency=USD")
j = contents.json()
pprint.pprint(j)
这表明:
{u'data': {u'average_price': {u'precision': 5,
u'value': u'0.00148',
u'value_int': 148},
u'closing_price': {u'precision': 5,
u'value': u'0.00152990',
u'value_int': 152},
u'date': 1392701954,
u'max_price': {u'precision': 5,
u'value': u'0.00154900',
u'value_int': 154},
u'min_price': {u'precision': 5,
u'value': u'0.00141000',
u'value_int': 141},
u'opening_price': {u'precision': 5,
u'value': u'0.00150000',
u'value_int': 150},
u'units_traded': {u'precision': 8,
u'value': u'15946541.33311552',
u'value_int': 1594654133311552L},
u'volume_1day': {u'precision': 8,
u'value': u'15946541.33311552',
u'value_int': 1594654133311552L},
u'volume_7day': {u'precision': 8,
u'value': u'114969451.70386628',
u'value_int': 11496945170386628L}},
u'status': u'success'}
现在,我们只需要遍历这些数据即可获得您想要的内容。基于你的代码片段,我猜你想要date和average_price字段。首先,我们需要data
字段(尽管您也应该检查status
)。
data = j['data']
现在,您需要日期:
from datetime import datetime
dt = datetime.fromtimestamp( data['date'] )
和平均价格。然而,这有几个子领域。让我们抓住它的浮点版本,然后转换为float:
avg_price = float( data['average_price']['value'] )
现在打印出来......
print 'Date: {0} Avg Price: {1}'.format(dt, avg_price)
你有它:
Date: 2014-02-18 00:39:14 Avg Price: 0.00148
答案 1 :(得分:0)
问题是contents.json()返回一个字典,你正在尝试访问这个字典键“{”data“:{”date“,”average_price“}}”这是不对的。这就是为什么你得到TypeError:unhashable类型:'dict'
请在这里从contents.json()转储你的字典,这样我们就可以查看数据并修复它。