mila002 mila002 - 4 months ago 11
Ruby Question

Ruby - Each loop doesn't work

I have a file like this:

{
"total": 0,
"subtotal": 807,
"page": 1,
"per_page": 1000,
"search": "hostname",
"sort": {
"by": null,
"order": null
},
"results": {"aaa-test01.myname.com":{"hostname":"aaa-test01","networking":"{\"hostname\"=>\"aaa-test01\", \"mtu\"=>1500, \"netmask\"=>\"255.255.255.224\", \"primary\"=>\"eth0\"}"}, "osilek":{"networking":"{\"hostname\"=>\"osilek.myname.com\", \"mtu\"=>1500, \"netmask\"=>\"255.255.255.128\", \"netmask6\"=>\"ffff:ffff:ffff:ffff::\",\"primary\"=>\"eth1\"}"}}
}


I want to have a hash like this

g = {"aaa_test01.myname.com"=> "aaa-test01", "osilek.myname.com" => "osilek"}


The keys in this hash must be the same as keys in results, values must be the same sa values of hostname from the results.
I have a code:

#!/usr/bin/ruby

require 'rubygems'
require 'json'

data = JSON.load File.new("any.txt")
results = data["results"]

results.each do |key, hash|
hash.select! {|k,v| k == "networking"}
end
results.each do |key, h|
h.each do |key, hash|
#puts hash.select! {|k,v| k == "hostname"}
hash = JSON.parse hash.gsub('=>', ':')
hash.select! {|k,v| k == "hostname"}
new_h = h.inject({}) {|new_h, (k,v)| new_h.merge(key => hash.values)}
puts g = results.inject({}) {|g, (key, new_h)| g.merge(key => new_h.values)}
end
end


In this step
new_h = h.inject({}) {|new_h, (k,v)| new_h.merge(key => hash.values)}
everything looks ok, there I get
new_h = {{"networking"=>["aaa-test01"]}, {"networking"=>["osilek"]}}
. But in the next step instead g hash I get the results hash before entering the loop. The loop doesn't work well and I completley don't know why. Can You help me to fix it?

Answer

I rly dont know where is problem in your code, but you can do it like this:

any.txt

{
  "total": 0,
  "subtotal": 807,
  "page": 1,
  "per_page": 1000,
  "search": "hostname",
  "sort": {
    "by": null,
    "order": null
  },
  "results": {"aaa-test01.myname.com":{"hostname":"aaa-test01","networking":"{\"hostname\"=>\"aaa-test01\", \"mtu\"=>1500, \"netmask\"=>\"255.255.255.224\", \"primary\"=>\"eth0\"}"}, "osilek":{"networking":"{\"hostname\"=>\"osilek.myname.com\", \"mtu\"=>1500, \"netmask\"=>\"255.255.255.128\", \"netmask6\"=>\"ffff:ffff:ffff:ffff::\",\"primary\"=>\"eth1\"}"}}
 }

process.rb

require 'json'

json = JSON.load(File.new("any.txt"))

export = json['results'].each_with_object({}) do |(k, h), exp|
  next unless h['networking']
  network = JSON.parse(h['networking'].gsub('=>', ':'))
  exp[k] = network['hostname'] unless network['hostname'].to_s.strip.empty?
end

p export
# {"aaa-test01.myname.com"=>"aaa-test01", "osilek"=>"osilek.myname.com"}

I hope this helps.