Home > Net >  Parsing Hash in Ruby
Parsing Hash in Ruby

Time:09-08

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?

{
  "RequestData":{
    "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
          }
        ]
      }
    ]
  },
  "RequestResult":{
    "Success":true
  }
}

CodePudding user response:

anything like this?

traffic_group = h[:RequestData][: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