I tried with map and flat.map to restructure a json file (here is a sample it), with ruby from:
a= {
"_nb": {
"$nb": "55dd0"
},
"conf": "linux"
}
to
{
"_nb": "55dd0",
"conf": "linux"
}
or
{
"$nb": "55dd0",
"conf": "linux"
}
Could anyone point me in the right direction, please?
NOTE: So far I add this solution implemented which returns a NoMethodError.. Hope this will help you both user1934428 & Cary Swoveland ..
File.open("src.json", "w") do |f|
hash_data = JSON.parse(File.read(a))
hash = hash_data.to_s
hash.each do |key, value|
if key == "_id"
hash[value] = value.values.first
end
end
f.puts(hash)
end
A first step might be:
hash = {
"_nb": {
"$nb": "55dd0"
},
"conf": "linux"
}
hash.transform_values { |value| value.is_a?(Hash) ? value.values.first : value }
#=> {:_nb=>"55dd0", :conf=>"linux"}
Note: This only works when the nesting is not deeper than one level and when the nested array has only one key/value pair.