2014-01-23 225 views
1

我有一個JSON列表,如:對JSON值進行排序?

response = '{"ContainsErrors":false,"Result":[{"Name":"Aegypten","IsoCode":"EG"},{"Name":"Aequatorialguinea","IsoCode":"GQ"},{"Name":"Aethiopien","IsoCode":"ET"},{"Name":"Afghanistan","IsoCode":"AF"},{"Name":"Albanien","IsoCode":"AL"},{"Name":"Algerien","IsoCode":"DZ"},{"Name":"Angola","IsoCode":"AO"},{"Name":"Antigua und Barbuda","IsoCode":"AG"},{"Name":"Argentinien","IsoCode":"AR"},{"Name":"Australien","IsoCode":"AU"},{"Name":"Bahamas","IsoCode":"BS"}]}' 

我怎樣才能得到它的名字後排序?

response.sort_by { |k, v| v["Name"] } 

不起作用。

什麼工作是:

response = RestClient.get("#{Settings.itineris.url}/de/RepInfo/#{action}") 
#response = '{"ContainsErrors":false,"Result":[{"Name":"Aegypten","IsoCode":"EG"},{"Name":"Aequatorialguinea","IsoCode":"GQ"},{"Name":"Aethiopien","IsoCode":"ET"},{"Name":"Afghanistan","IsoCode":"AF"},{"Name":"Albanien","IsoCode":"AL"},{"Name":"Algerien","IsoCode":"DZ"},{"Name":"Angola","IsoCode":"AO"},{"Name":"Antigua und Barbuda","IsoCode":"AG"},{"Name":"Argentinien","IsoCode":"AR"},{"Name":"Australien","IsoCode":"AU"},{"Name":"Bahamas","IsoCode":"BS"}]}' 

JSON.load(response)['Result'] 

結果是未排序的列表。我怎樣才能得到一個國家名稱的有序列表?

回答

6

你有一個字符串作爲迴應。它在操作之前,你應該把它轉換爲Hash

response = '{"ContainsErrors":false,"Result":[{"Name":"Aegypten","IsoCode":"EG"}]}' 
require 'json' 
hash = JSON.parse(response) 

,然後做你想做的:

hash['Result'].sort_by { |v| v["Name"] } 
#       ⇑ v here since it’s an array of hashes 

要獲得國名的有序列表:

hash['Result'].map { |v| v["Name"] }.sort 
+0

嗯,它不工作,所以我試着用JSON.load(response)['Result']。sort_by {| k,v | v [「Name」]}但它也失敗了。 – StandardNerd

+0

您是否注意到我在我的示例中連接了您的輸入以適應頁面寬度? – mudasobwa

+0

@Michael我使用Ruby 1.9.3,錯誤是「NoMethodError」和'block in rest_request','each','sort_by'... – StandardNerd