2012-11-18 88 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

我不知道我在做什麼錯,但是當我現在運行這個時,我得到一個錯誤: –