Gabriel Phua Gabriel Phua - 3 months ago 16
JSON Question

Python-JSON - How to parse API output?

I'm pretty new.

I wrote this python script to make an API call from blockr.io to check the balance of multiple bitcoin addresses.

The contents of btcaddy.txt are bitcoin addresses seperated by commas. For this example, let it parse this.

import urllib2
import json


btcaddy = open("btcaddy.txt","r")


urlRequest = urllib2.Request("http://btc.blockr.io/api/v1/address/info/" + btcaddy.read())
data = urllib2.urlopen(urlRequest).read()
json_data = json.loads(data)

balance = float(json_data['data''address'])
print balance

raw_input()


However, it gives me an error. What am I doing wrong? For now, how do I get it to print the balance of the addresses?

Answer

You've done multiple things wrong in your code. Here's my fix. I recommend a for loop.

import json
import urllib

addresses = open("btcaddy.txt", "r").read()

base_url = "http://btc.blockr.io/api/v1/address/info/"
request = urllib.urlopen(base_url+addresses)
result = json.loads(request.read())['data']
for balance in result:
    print balance['address'], ":" , balance['balance'], "BTC"

You don't need an input at the end, too.