如何在保持 ruby​​ on Rails 中的顺序的同时从哈希渲染 json 响应?

发布于 2024-08-20 16:37:20 字数 305 浏览 10 评论 0原文

我无法根据国家/地区名称及其国家/地区代码的哈希数据结构在 ruby​​ on Rails 中呈现 json 响应: { "AF"=>"阿富汗", "AL"=>"阿尔巴尼亚", "DZ" =>"Algeria", ... },以便 json 响应的条目按字母顺序排列,如下所示:

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

根据我的理解,问题在于 ruby​​ 哈希本身没有顺序概念。所以响应是完全随机的。

感谢您的帮助!

马丁

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟燃烟灭 2024-08-27 16:37:20

您可以使用 ActiveSupport::OrderedHash

示例案例:

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

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
情未る 2024-08-27 16:37:20

一个哈希数组怎么样:

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

How about an array of hashes like:

[{ "AF"=>"Afghanistan"}, {"AL"=>"Albania"}, {"DZ"=>"Algeria"}, ... ]
优雅的叶子 2024-08-27 16:37:20

感谢之前的答案(-> westoque),我最终在 Rails 初始化程序文件夹中猴子修补哈希类,如下所示:

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

并在从控制器渲染时调用 to_json 。
多谢!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文