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']
結果是未排序的列表。我怎樣才能得到一個國家名稱的有序列表?
嗯,它不工作,所以我試着用JSON.load(response)['Result']。sort_by {| k,v | v [「Name」]}但它也失敗了。 – StandardNerd
您是否注意到我在我的示例中連接了您的輸入以適應頁面寬度? – mudasobwa
@Michael我使用Ruby 1.9.3,錯誤是「NoMethodError」和'block in rest_request','each','sort_by'... – StandardNerd