2012-11-18 73 views
6

我目前正在从discogs API(mp3标签数据)获取JSON数据,并希望按键的值排序结果。在这种情况下,我正在尝试获取Guns n Roses歌曲的数据,并且输出结果是1988年作为第一个,而数据实际上有1987年的记录。我如何对这些数据进行排序,以便可以通过排序数据(最新的olderst)。下面的代码按键或值排序,但那不是我想要的。请帮忙。按键排序JSON数据值

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 
+3

如果您包含JSON数据的样本,我会提供帮助。 –

+0

通过它的外观,你正在使用[这个API](http://www.discogs.com/developers/resources/database/search-endpoint.html)。 –

回答

12

你可以使用列表理解和sorted()功能如下:

# 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']) 

或:

In [79]: from operator import itemgetter 

In [80]: sorted(results, key=itemgetter('year')) 
+0

比你,这就像一个魅力,你可以告诉我,我是一个新手,还有很长的路要走.. –

1

要排序的词典列表,使用methodcaller要对其进行排序的关键;你想排序结果列表,而不是包含的字典。此外,一些条目不一年,这可能导致错误:

from operator import methodcaller 

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

methodcaller定义为json_object['results']每个条目基本上都会做entry.get('year', None),给sorted方法的价值排序上。

您应该不是使用readlines()来读取您的JSON响应,它会错误地解释新行。让json库不读,而不是(注意​​,没有s末):

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

我是新来这个论坛,我无法发布JSON,因为它说我有几个字符留下来发布... –

+0

看看[我如何格式化我的代码块?](http:// meta。 stackexchange.com/q/22186)寻求更多帮助。 –

+0

我不知道我在做什么错,但是当我现在运行这个时,我得到一个错误: –