Reputation: 3
This is the code I have been using:
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")
This outputs:
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}
I would like to know how to only print the price
or the volume
for the second API response, since I can't do it the same way I did in the first function, i.e.:
avg24 = info["24h_avg"]
Upvotes: 0
Views: 132
Reputation: 18438
What the server is returning you can be understood (if it helps) as a "text-formatted" python dictionary (see type dict documentation)
So you have to load that Json text into a dict, and then you can easily refence items in it.
Hopefully running this will help you see how it works:
#!/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']
Which outputs:
{"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
Upvotes: 0
Reputation: 970
You can go multiple levels deep in a dictionary. So to get price
from the maxcoin
dictionary, simply do:
maxcoin_price = maxcoin['ticker']['price']
Upvotes: 1