我有一个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']
结果是未排序的列表。如何获得有序的国家/地区名称列表?
答案 0 :(得分: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