Sorting JSON data by keys value

Prem Minister picture Prem Minister · Nov 18, 2012 · Viewed 17.1k times · Source

I am currently getting JSON data from the discogs API (mp3 tag data) and wish to sort the results by the key's value. In this case I am trying to get data for a Guns n Roses song and the output has 1988 as the first one while the data actually has a record from 1987. How can I sort this data so that I can get to the sorted data by year (olderst to newest). The code below sorts by either key or value but thats 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

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Nov 18, 2012

You could use list-comprehension and sorted() function 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'))