Parsing Hash in Ruby

Viewed 52

Bit lost while parsing the hash, actually i want to retrieve the id for "HTTP get traffic" which is in this case 9.? can anyone help?

gettest = {
  "Groups" => [
    {
      "GroupName" => {"TextId" => "Hardware"},
      "Tests" => [
        {"Description"=>{"TextId"=>"ODU current measurement"}, "Id" => 0}
      ]
    },
    {
      "GroupName"=>{"TextId"=>"LAN"},
      "Tests" => [
        {"Description" => {"TextId" => "Ethernet status"}, "Id" => 2},
        {"Description" => {"TextId" => "Number of TCP Sessions"}, "Id" => 3}
      ]
    },
    {
      "GroupName" => {"TextId" => "Satellite connection"},
      "Tests" => [
        {"Description" => {"TextId" => "Physical layer status"}, "Id" => 4},
        {"Description" => {"TextId" => "Data link layer status"}, "Id" => 5},
        {"Description" => {"TextId" => "Network layer status"}, "Id" => 6}
      ]
    },
    {
      "GroupName" => {"TextId" => "Software"},
      "Tests" => [
        {"Description" => {"TextId" => "Software"}, "Id" => 1}
      ]
    },
    {
      "GroupName" => {"TextId" => "Traffic"},
      "Tests" => [
        {"Description" => {"TextId" => "Ping traffic"}, "Id" => 7},
        {"Description" => {"TextId" => "DNS traffic"}, "Id" => 8},
        {"Description" => {"TextId" => "HTTP get traffic"}, "Id" => 9}
      ]
    }
  ]
}
1 Answers

anything like this?

traffic_group = gettest['Groups'].find do |group|
  group['GroupName']['TextId'] == 'Traffic'
end
if traffic_group 
  http_get_traffic = traffic_group['Tests'].find do |test| 
    test['Description']['TextId'] == 'HTTP get traffic' 
  end
  if http_get_traffic
    http_get_traffic_id = http_get_traffic['Id']
    puts "HTTP get traffic id: #{http_get_traffic_id}"
  else
    puts 'no http get traffic node found'
  end
else
  puts 'no traffic group found'
end
Related