I am trying to fetch JSON data using the discogs API, but the code doesnt seem to give the output I see when I paste the data in a browser as raw. Kindly let me know what I am doing wrong here as I am new to Python. I was looking to get the output for title, images. Thanks!
Python:
import urllib
import urllib2
import json
url = 'http://api.discogs.com/masters/66271'
request = urllib2.Request('http://api.discogs.com/masters/66271')
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_raw= response.readlines()
json_object = json.loads(json_raw[0])
print json_object
for row in json_object:
print row
print row['title']
wrong output:
styles
genres
videos
title
main_release
main_release_url
uri
artists
versions_url
year
images
resource_url
tracklist
id
data_quality
You should not use
.readlines()
. Let thejson
library do the reading:Note the function name,
.load()
, nos
at the end.The object returned is a dictionary; each of the strings you see is a key into that dictionary. You need to specify what titles you'd want; the
tracklist
andvideos
entries both have a list of items with titles; here is how you'd print thetracklist
entry titles:Which prints: