如何在保持 ruby on Rails 中的顺序的同时从哈希渲染 json 响应?
我无法根据国家/地区名称及其国家/地区代码的哈希数据结构在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
ActiveSupport::OrderedHash
示例案例:
You can use
ActiveSupport::OrderedHash
Sample Case:
一个哈希数组怎么样:
How about an array of hashes like:
感谢之前的答案(-> westoque),我最终在 Rails 初始化程序文件夹中猴子修补哈希类,如下所示:
并在从控制器渲染时调用 to_json 。
多谢!
thanks to previous answers (-> westoque) i ended up to monkey patch the Hash Class in rails initializers folder like that:
and called to_json when rendered from the controller.
Thanks a lot!