这是我一直在使用的代码:
def get_api(url):
#Funtion to ask and output the price
x = urlopen( url )
info = json.loads(x.read())
x.close()
avg24 = info["24h_avg"]
gbp_volume = info["volume_percent"]
last = info["last"]
print avg24
print gbp_volume
print last
def max(url):
g = urlopen( url )
max_info = json.loads(g.read())
g.close()
maxcoin = max_info
pprint(maxcoin)
get_api("https://api.bitcoinaverage.com/ticker/global/GBP/")
max("https://www.cryptonator.com/api/ticker/max-btc")
输出:
237.47
1.5
233.6
{u'error': u'',
u'success': True,
u'ticker': {u'base': u'MAX',
u'change': u'0.00000062',
u'price': u'0.00002303',
u'target': u'BTC',
u'volume': u'466841.69495860'},
u'timestamp': 1417038842}
我想知道如何仅为第二个API响应打印price
或volume
,因为我无法像在第一个函数中那样执行此操作,即:
avg24 = info["24h_avg"]
答案 0 :(得分:1)
您可以在字典中深入多个级别。因此,要从price
词典中获取maxcoin
,只需执行以下操作:
maxcoin_price = maxcoin['ticker']['price']
答案 1 :(得分:0)
服务器返回的内容可以被理解(如果有帮助)作为“文本格式”的python字典(参见类型dict documentation)
所以你必须将Json文本加载到dict中,然后你可以轻松地为其中的项目进行补充。
希望运行此功能可以帮助您了解它的工作原理:
#!/usr/bin/env python
import json
import pprint
json_resp = ('{"ticker":{"base":"MAX","target":"BTC","price":"0.00002255",'
'"volume":"465146.31939802","change":"-0.00000001"},'
'"timestamp":1417040433,"success":true,"error":""}')
print json_resp
json_dict = json.loads(json_resp)
print "Loaded a %s containing %s" % (type(json_dict), pprint.pformat(json_dict))
print "The ticker is a %s containing: %s" % (
type(json_dict['ticker']),
pprint.pformat(json_dict['ticker'])
)
print "Price: %s" % json_dict['ticker']['price']
print "Volume: %s" % json_dict['ticker']['volume']
哪个输出:
{"ticker":{"base":"MAX","target":"BTC","price":"0.00002255","volume":"465146.31939802","change":"-0.00000001"},"timestamp":1417040433,"success":true,"error":""}
Loaded a {u'timestamp': 1417040433, u'ticker': {u'volume': u'465146.31939802', u'price': u'0.00002255', u'base': u'MAX', u'target': u'BTC', u'change': u'-0.00000001'}, u'success': True, u'error': u''} containing {u'error': u'',
u'success': True,
u'ticker': {u'base': u'MAX',
u'change': u'-0.00000001',
u'price': u'0.00002255',
u'target': u'BTC',
u'volume': u'465146.31939802'},
u'timestamp': 1417040433}
The ticker is a <type 'dict'> containing: {u'base': u'MAX',
u'change': u'-0.00000001',
u'price': u'0.00002255',
u'target': u'BTC',
u'volume': u'465146.31939802'}
Price: 0.00002255
Volume: 465146.31939802