Iterating through a JSON object
I am trying to iterate through a JSON object to import data, i.e. title and link. I can't seem to get to the content that is past the :
.
JSON:
[
{
"title": "Baby (Feat. Ludacris) - Justin Bieber",
"description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark",
"link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq",
"pubDate": "Wed, 28 Apr 2010 02:37:53 -0400",
"pubTime": 1272436673,
"TinyLink": "http://tinysong.com/d3wI",
"SongID": "24447862",
"SongName": "Baby (Feat. Ludacris)",
"ArtistID": "1118876",
"ArtistName": "Justin Bieber",
"AlbumID": "4104002",
"AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw",
"LongLink": "11578982",
"GroovesharkLink": "11578982",
"Link": "http://tinysong.com/d3wI"
},
{
"title": "Feel Good Inc - Gorillaz",
"description": "Feel Good Inc by Gorillaz on Grooveshark",
"link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI",
"pubDate": "Wed, 28 Apr 2010 02:25:30 -0400",
"pubTime": 1272435930
}
]
I tried using a dictionary:
def getLastSong(user,limit):
base_url = 'http://gsuser.com/lastSong/'
user_url = base_url + str(user) + '/' + str(limit) + "/"
raw = urllib.urlopen(user_url)
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
#filtering and making it look good.
gsongs = []
print json_object
for song in json_object[0]:
print song
This code only prints the information before :
.
(ignore the Justin Bieber track :))
Solution 1:
I believe you probably meant:
from __future__ import print_function
for song in json_object:
# now song is a dictionary
for attribute, value in song.items():
print(attribute, value) # example usage
NB: You could use song.iteritems
instead of song.items
if in Python 2.
Solution 2:
Your loading of the JSON data is a little fragile. Instead of:
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
you should really just do:
json_object = json.load(raw)
You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0]
, you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:
, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song]
.
None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.
Solution 3:
This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.
import json
def main():
# create a simple JSON array
jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'
# change the JSON string into a JSON object
jsonObject = json.loads(jsonString)
# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))
pass
if __name__ == '__main__':
main()
Solution 4:
After deserializing the JSON, you have a python object. Use the regular object methods.
In this case you have a list made of dictionaries:
json_object[0].items()
json_object[0]["title"]
etc.