Logstash ruby json parsing Issue

Hi ,
I need to poll http endpoint from logstash using http_poller plugin and parse the json response to fetch the values and derive custom fields based on that.
Below is my response sample json output that need to parsed and derive some fields based on that.

{ "response" :  {
      "root": {
          "mode": "master",
          "node-id": "master.host.com"
          "connected-slave": ["slave.host1.corp.com","slave.host2.corp.com"] 
      }
   }
}

Below is my logstash (version 6.6.0) code in ruby:

if ([response]) {
  ruby {
    code => "
        require 'json'
        jsondata = event.get('response')
        parsed = JSON.parse(jsondata)
        parsed['root'].each { |hash|
         if #{hash['mode']} == 'master'
           event.set('df_mode', 'master')
         end
        }
    "
  }
}

While running this configuration, I am running into "Hash cannot convert to String ruby exception". And I tried other ways also but not helped though. Please provide some light or with sample code, how i could get the values of each key which i need to set as custom fields values.

Thanks
Sukumar C

Why use ruby? If you have valid JSON in a field called response (your JSON is not valid, it is missing a comma after the value of "node-id") you can parse it using a json filter then reference the fields directly

filter {
    json { source => "message" remove_field => [ "message" ] } }

    if [response][root][mode] == "master" {
        mutate { copy => { "[response][root][mode]" => "df_mode" } }
    }
}

Reason for using ruby is i need to loop the response array with expected array for one of the json array field. If it is just copying the fields then i could have think of logstash code. I feel it is easy to do in ruby. Please advise.
But I am able to achieve it using ruby now. Thanks

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.