展平嵌套的json对象

pgu*_*rio 5 ruby arrays hash json

我正在寻找一种方法,将"json"哈希扁平化为扁平哈希,但将路径信息保存在扁平化键中.例如:

h = {"a" => "foo", "b" => [{"c" => "bar", "d" => ["baz"]}]}
Run Code Online (Sandbox Code Playgroud)

压扁(h)应该返回:

{"a" => "foo", "b_0_c" => "bar", "b_0_d_0" => "baz"}
Run Code Online (Sandbox Code Playgroud)

Hck*_*Hck 14

这应该可以解决您的问题:

h = {'a' => 'foo', 'b' => [{'c' => 'bar', 'd' => ['baz']}]}

module Enumerable
  def flatten_with_path(parent_prefix = nil)
    res = {}

    self.each_with_index do |elem, i|
      if elem.is_a?(Array)
        k, v = elem
      else
        k, v = i, elem
      end

      key = parent_prefix ? "#{parent_prefix}.#{k}" : k # assign key name for result hash

      if v.is_a? Enumerable
        res.merge!(v.flatten_with_path(key)) # recursive call to flatten child elements
      else
        res[key] = v
      end
    end

    res
  end
end

puts h.flatten_with_path.inspect
Run Code Online (Sandbox Code Playgroud)