展平嵌套的json对象

时间:2012-05-23 02:24:18

标签: ruby arrays json hash

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

h = {"a" => "foo", "b" => [{"c" => "bar", "d" => ["baz"]}]}
压扁(h)应该返回:

{"a" => "foo", "b_0_c" => "bar", "b_0_d_0" => "baz"}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我有类似的问题并在此处提出 Best way to produce a flattened JSON (denormalize) out of hierarchical JSON in Ruby有可能的解决方案

我的解决方案是最佳解决方案还是有更好的方法?