mila002 mila002 - 4 months ago 9
Ruby Question

How to fix an "each" loop that doesn't work

I have a file:

{
"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 the keys in results, values must be the same as the values of hostname from the results.

I have this 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

new_h = h.inject({}) {|new_h, (k,v)| new_h.merge(key => hash.values)}


everything looks ok, and I get

new_h = {{"networking"=>["aaa-test01"]}, {"networking"=>["osilek"]}}


But in the next step instead of the
g
hash I get the
results
hash before entering the loop. The loop doesn't work well and I don't know why.

Answer

I don't know where the problem is 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"}
Comments