Smooth json nested object

I am looking for a method that smooths the "json" hash into a flattened hash, but stores the path information in flattened keys. For instance:

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

flatten (h) should return:

{"a" => "foo", "b_0_c" => "bar", "b_0_d_0" => "baz"}
+5
source share
2 answers

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
+12
source

I have a similar question and raised it here. The best way to create flattened JSON (denormalize) from hierarchical JSON in Ruby with a possible solution

Is my solution optimal or is there a better way?

0
source

All Articles