\"Afghanistan\", \"AL\"=>\"Albania\", \"DZ\"=>" />
开发者

How can i render a json response from a hash while maintaining order in ruby on rails?

i am failing to render a json response in ruby on rails from a hash datastructure of country-names 开发者_如何学Pythonwith 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


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


How about an array of hashes like:

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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜