简体   繁体   中英

Flatten a nested json object

I'm looking for a method that will flatten a "json" hash into a flattened hash but keep the path information in the flattened keys. For example:

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

flatten(h) should return:

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

This should solve your problem:

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

I'm having a similar question and raised it here Best way to produce a flattened JSON (denormalize) out of hierarchical JSON in Ruby with a possible solution

Is my solution an optimal one or is there any better way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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