Gabriel Phua Gabriel Phua - 1 year ago 109
JSON Question

Python-JSON - How to parse API output?

I'm pretty new.

I wrote this python script to make an API call from 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("" +
data = urllib2.urlopen(urlRequest).read()
json_data = json.loads(data)

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


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 Source

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 = ""
request = urllib.urlopen(base_url+addresses)
result = json.loads(['data']
for balance in result:
    print balance['address'], ":" , balance['balance'], "BTC"

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download