1

I have a JSON list like:

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"}]}'

How can I get it sorted after names?

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

doesn't work.

What does work is:

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

The result is an unsorted List. How can I get an ordered list of country names?

1 Answer 1

6

You have a string in response. Before operating on it, you should convert it to Hash:

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

and then do whatever you want:

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

To get an ordered list of country names:

hash['Result'].map { |v| v["Name"] }.sort
Sign up to request clarification or add additional context in comments.

6 Comments

hmm, it doesn't work and so i tried with JSON.load(response)['Result'].sort_by { |k, v| v["Name"] } but it failed, too.
Did you noticed that I concatenated your input in my example to fit the page width?
@Michael i use Ruby 1.9.3 and the error is "NoMethodError" and block in rest_request', 'each', sort_by' ...
@ArupRakshit that’s nonsense. require doesn’t need to be on top.
@ArupRakshit what if you need to require smth depending on condition? Have you never seen if 'win' ; require '_win' ; else require '_nix' ; end ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.