展平嵌套的JSON对象

展平嵌套的JSON对象

本文介绍了展平嵌套的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找,将展平JSON散列成一个扁平的哈希值,但保持在扁平按键的路径信息的方法。
例如:

  H = {A=> 富,B=> [{C=> 酒吧,D=> [巴兹]}]}

扁平化(H)应返回:

  {A=> 富,b_0_c=> 酒吧,b_0_d_0=> 巴兹}


解决方案

这应该解决您的问题:

  H = {'A​​'=> '富','B'=> [{'C'=> '酒吧','D'=> ['巴兹']}]}模块可枚举
  高清flatten_with_path(PARENT_ preFIX =无)
    RES = {}    self.each_with_index做| ELEM,我|
      如果elem.is_a?(阵列)
        K,V = ELEM
      其他
        K,V = I,ELEM
      结束      关键= PARENT_ preFIX? #{PARENT_ preFIX}#[KP}:K#的结果散列指定的键名      如果v.is_a?枚举
        res.merge!(v.flatten_with_path(密钥))#递归调用压扁子元素
      其他
        RES [关键] = V
      结束
    结束    水库
  结束
结束把h.flatten_with_path.inspect

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

这篇关于展平嵌套的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:13