[英]How do I get a specific part from this JSON response?
這是我一直在使用的代碼:
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"]
您可以深入字典中的多個級別。 因此,要從maxcoin
詞典中獲取price
,只需執行以下操作:
maxcoin_price = maxcoin['ticker']['price']
服務器返回的內容可以理解為(如果有幫助的話)為“文本格式”的python字典(請參見type dict文檔 )
因此,您必須將該Json文本加載到字典中,然后才能輕松引用其中的項目。
希望運行它可以幫助您了解其工作原理:
#!/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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.