Catalina Cenan
Catalina Cenan

Reputation: 319

merge two or more hashes from array in one json file

The issue that I'm facing is when I'm trying to automate a terraform script for bootstrap VMs. I keep all the templates in json files and depending on instance it will take one, two or more templates to create the node json file. My code looks like:

template.each do |t|
  node = JSON.parse(File.read("./terraform/node/#{t}.json"))
  atr << node.each { |k, v| puts "#{k}: #{v}" }
  concatenated = atr.flatten
  temp = concatenated  
  File.open("./terraform/node/#{instance_name}.json","w") do |f|
    f.puts JSON.pretty_generate(temp)
  end
end

The output file looks like:

[{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}, {"apache"=>{"listen_ports"=>["80", "443"]}}, {"tags"=>[]}]

The issue is that inside the array we have the exact template stored in erb :

{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}
{"tags"=>[]} ...

What I want is a valid json with the content of templates like:

 {"haproxy"=>{"app_server_role"=>["s1", "s2"]}, "apache"=>{"listen_ports"=>["80", "443"]}, {"tags"=>[]}

Upvotes: 0

Views: 356

Answers (1)

Anthony
Anthony

Reputation: 15967

output_file = [{"haproxy"=>{"app_server_role"=>["s1", "s2"]}}, {"apache"=>{"listen_ports"=>["80", "443"]}}, {"tags"=>[]}]

output_file.each_with_object({}) { |h, h2| h2.merge!(h) }
 => {"haproxy"=>{"app_server_role"=>["s1", "s2"]}, "apache"=>{"listen_ports"=>["80", "443"]}, "tags"=>[]}

another great option suggested by mudasobwa:

output_file.reduce(&:merge)

Upvotes: 1

Related Questions