简体   繁体   English

如何将带有表示嵌套的键的哈希转换为嵌套哈希

[英]How to convert hash with keys representing nesting into a nested hash

I need to convert the following hash:我需要转换以下哈希:

{
  "item[0][size]" => "12",
  "item[0][count]" => "1"
}  

to this:对此:

{
  "item": {
    "0": {
      "size": "12",
      "count": "1"
    }
  }
}  

Could you please advice on how to achieve that most gracefully?您能否就如何最优雅地实现这一目标提出建议? Maybe I can reuse some ActionPack's utility method that is used for parsing parameter strings?也许我可以重用一些 ActionPack 用于解析参数字符串的实用方法?

You can reuse a rack lib method Rack::Utils.parse_nested_query您可以重用rack库方法Rack::Utils.parse_nested_query

require "rack"
def p p
  Rack::Utils.parse_nested_query(p)                                               
end
p 'item[0][size]=12' # => {"item"=>{"0"=>{"size"=>"12"}}}

Found here .这里找到。

After some research I found a way to parse nested query keys using http://apidock.com/rails/Rack/Utils/parse_nested_query :经过一番研究,我找到了一种使用http://apidock.com/rails/Rack/Utils/parse_nested_query解析嵌套查询键的方法:

Rack::Utils.parse_nested_query('item[0][size]')
=> {
  "item" => {
    "0" => {
      "size" => nil
    }
  }
}

So it's now possible to do:所以现在可以这样做:

items_string = item_hash.to_a.map { |row| row.join('=') }.join('&')
result = Rack::Utils.parse_nested_query(items_string)

=> {
  "item" => {
    "0" => {
       "size" => "12",
      "count" => "1"
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM