【问题标题】:How can i render a json response from a hash while maintaining order in ruby on rails?如何在保持 ruby​​ on rails 顺序的同时从哈希渲染 json 响应?
【发布时间】:2010-02-10 02:21:56
【问题描述】:

我无法从带有国家代码的国家名称哈希数据结构中以 ruby​​ on rails 呈现 json 响应:{ "AF"=>"Afghanistan", "AL"=>"Albania", "DZ "=>"Algeria", ... },因此 json 响应的条目按字母顺序排列如下:

{ "AF":"阿富汗", "AL":"阿尔巴尼亚", "DZ"=>"阿尔及利亚" ... }

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

感谢您的帮助!

马丁

【问题讨论】:

    标签: ruby-on-rails json hash render


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 嘿韦斯托克!这正是我一直在寻找的。​​span>
    【解决方案2】:

    哈希数组怎么样:

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

    【讨论】:

    • 如果 HTTP 响应需要采用该特定格式,这将不起作用。
    【解决方案3】:

    感谢之前的回答 (-> westoque),我最终在 rails initializers 文件夹中修改了哈希类,如下所示:

    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。 非常感谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多