views:

239

answers:

3

hey out there, i am failing to render a json response in ruby on rails from a hash datastructure of country-names with their country-codes: { "AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria", ... }, so that the json response has its entries alphabetically ordered like this:

{ "AF":"Afghanistan", "AL":"Albania", "DZ"=>"Algeria" ... }

the problem, for my understanding, is, that a ruby hash has in itself no notion of order. so the response is totally random.

thanks for any help!

martin

A: 

How about an array of hashes like:

[{ "AF"=>"Afghanistan"}, {"AL"=>"Albania"}, {"DZ"=>"Algeria"}, ... ]
Beerlington
This won't work if the HTTP response needs to be in that specific format.
Jonathan Julian
+3  A: 

You can use ActiveSupport::OrderedHash

Sample Case:

hash = ActiveSupport::OrderedHash.new
hash["one"] = "one"
hash["two"] = "two"
hash["three"] = "three"
p hash            # Will give you the hash in reverse order
p hash.to_json    # Will give you a json with the ordered hash
westoque
Hey westoque! This was exactly i was looking for.
mtin79
A: 

thanks to previous answers (-> westoque) i ended up to monkey patch the Hash Class in rails initializers folder like that:

class Hash
 def to_inverted_ordered_hash
  copy = self.dup.invert.sort
  copy.inject(ActiveSupport::OrderedHash.new) {|hash, i|  hash[i[1]] =  i[0]; hash}
 end

 def to_ordered_hash
  copy = self.dup.sort
  copy.inject(ActiveSupport::OrderedHash.new) {|hash, i|  hash[i[1]] =  i[0]; hash}
 end
end

and called to_json when rendered from the controller. Thanks a lot!

mtin79