I want a single method which will update the content of Json which should work like below:
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')
In the above the keys zones and esxi are Array in hash. Example josn content below
{"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"}]
}]
}
}
The following code works when there is no array in 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
In the above code find.tree is my method which returns value inside the path for eg., 'profile/zones', if no args passed it will return entire json content