drinkingwine
Registered User
Registered User
Posts: 6
Joined: Wed May 11, 2016 3:26 am
Country: United States

Python help...

Sat May 14, 2016 11:53 pm

Can someone please help me out here.

I have this python snippet that works for calls to wunderground.com but fails on calls to audiodb.

import urllib2
import json
f = urllib2.urlopen('http://www.theaudiodb.com/api/v1/json/1/searchtrack.php?s=adele&t=hello')
json_string = f.read()
parsed_json = json.loads(json_string)
album = parsed_json['track']['strAlbum']
print "Album is: %s" % (album)
f.close()

Air:Desktop ralph$ python audiodb.py
Traceback (most recent call last):
File "audiodb.py", line 6, in <module>
album = parsed_json['track']['strAlbum']
TypeError: list indices must be integers, not str
Air:Desktop ralph$

Obviously the audiodb.com json string is formatted differently. I looked at the manual for the function json.load, but the manual reads like an instruction guide for putting a satellite in orbit!

so, can anyone help with the code for album=parased.json [???] [???] to return the album name?

Thanks in advance.

-rp

User avatar
zag
Site Admin
Site Admin
Posts: 1195
Joined: Wed Jun 06, 2012 9:19 am
Country: United Kingdom

Re: Python help...

Sun May 15, 2016 8:20 am

Not a python man myself, but in php you have to loop through the results or just index the first item in the array using [0]['track']['strAlbum']

Something like that might work, but as I say, i'm not an expert.

drinkingwine
Registered User
Registered User
Posts: 6
Joined: Wed May 11, 2016 3:26 am
Country: United States

Re: Python help...

Sun May 15, 2016 2:30 pm

Thank you for your post! You got me looking at the function differently.

album = parsed_json['track'][0]['strAlbum'] is the what was needed...

It should have been so obvious when I looked at the manual...LOL

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

Thanks again...

Return to “Developers”