如何修复不起作用的“每个”循环

时间:2016-07-19 15:25:09

标签: ruby hash each

我有一个文件:

{
  "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\"}"
    }
  }
}

我想要像这样的哈希:

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

此哈希中的键必须与结果中的键相同,值必须与结果中的主机名值相同。

我有这段代码:

#!/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

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

一切看起来都不错,我得到了

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

但是在下一步而不是g哈希中,我在进入循环之前得到results哈希。循环不能很好地工作,我不知道为什么。

2 个答案:

答案 0 :(得分:1)

另一种方式:

data['results'].inject({}) do |hash, (k, v)|
  fallback = JSON.parse(v['networking'].gsub('=>', ':'))['hostname']
  hash.merge("#{k}": v['hostname'] || fallback)
end

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

答案 1 :(得分:0)

我不知道代码中的问题所在,但您可以这样做:

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"}