Sort JSON data by key value

I am currently retrieving JSON data from the discogs API (mp3 tag data) and want to sort the results by key value. In this case, I'm trying to get data for the song Guns n Roses, and the output is 1988, while the data actually has been recorded since 1987. How can I sort this data so that I can get sorted data by year (from oldest to newest). The code below is sorted by key or value, but this is not what I intended to get. Please, help.

import json import urllib2 request = urllib2.Request('http://api.discogs.com/database/search?sort=year&sort_order=asc&artist=%22Guns+N%27+Roses%22&track=%22Sweet+Child+O%27+Mine%22&format_exact=Album&type=master') 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]) for row in json_object['results']: try: from operator import itemgetter for k, v in sorted(row.items(), key=itemgetter(0)): print k, v except KeyError: pass 
+6
source share
2 answers

You can use the list-comprehension and sorted() functions for this:

 # filter json_object['results'] first, as some of the items are missing the key 'year' In [33]: results = [x for x in json_object['results'] if 'year' in x] In [34]: sorted(results, key=lambda x: x['year']) 

or:

 In [79]: from operator import itemgetter In [80]: sorted(results, key=itemgetter('year')) 
+12
source

To sort the list of dictionaries, use the methodcaller with the key to sort; You want to sort the list of results, not the contained dictionaries. Moreover, some records do not have a year, and this can lead to errors:

 from operator import methodcaller for row in sorted(json_object['results'], key=methodcaller('get', 'year', None)): # process the row dictionary 

The definition of methodcaller will basically do entry.get('year', None) for each entry in json_object['results'] , providing the sorted method sorted value for sorting.

You should not use readlines() to read your JSON response, this will interpret newlines incorrectly. Let the json library read it instead (note the .load() , no s at the end):

 response = urllib2.urlopen(request) json_object = json.load(response) 
+1
source

All Articles