使用路径更新JSON的功能(ex:profile/Zones/objects/object)



我想要一种将更新JSON的内容的方法,该方法应如下:

data = { "id"=>7913251, "domain"=>"domain.com", "ready"=>true, "create_starttime"=>"2018-08-30 05:57:14 -0500" }
update_json(data, 'profile/zones/0/esxi/1')

在上面的密钥区域和ESXI中是哈希中的数组。示例josn内容

{"profile"=>
  {"zones"=>
    [{"name"=>"cloud_group1",
      "is_main"=>true,
      "esxi"=>
       [{"id"=>7923451,
         "domain"=>"domain.com",
         "ready"=>true,
         "create_starttime"=>"2018-08-30 05:57:14 -0500",
         "create_stoptime"=>"2018-08-30 07:29:05 -0500"}]
    }]
  }
}

Hash中没有数组时,以下代码有效。

def update_json(data, path)
        components = path.split('/')
        if components.length > 1
          key = components[-1]
          path.slice! "/#{key}"
          find.tree(path)[key] = data
        else
          find.tree[path] = data
        end
        File.open(json_string, 'w') { |file| file.write(JSON.pretty_generate(find.tree)) }
      end # update_json

在上面的代码 find.tree 中是我的方法,它返回例如" for。"," profile/zones"的路径,如果没有args,则它将返回整个json content

我对方法tree()没有可见性,但是我会像以下示例一样处理任务:

hash.dig('profile', 'zones', 0, 'esxi')[0] = data

处理数组时,您不仅必须拆分path,还必须将索引转换为数字。如果find.tree()正常工作,

key = Integer(key) if key[/^d+$/]
find.tree(path)[key] = data

应该做这项工作。请注意,如果您的路径包含不是数组索引的数字,则条件是无用的。还要注意分配哈希时。您可能需要确保正确设置您的default_proc:https://stackoverflow.com/a/34621043/1288687

我希望您对此有所帮助。

最新更新