Logstash filter: Convert all fields in json to integer

Hi,
I have a json data of below format (in rubydebug output). I want to convert all the counter values to integer. with mutate filter plugin, i have to convert each counter to integer. However, this is a shortened data. i have a lot of counters. So i tried using the ruby code.. Ruby Code show below.
I get error "Ruby exception occurred: no implicit conversion of String into Integer" for this ruby code. I dont think the error is for value.to_i. its something to do with "event.set(['counters']['#{key}']".

{
"@timestamp" => 2019-05-11T14:37:56.933Z,
"component-name" => "myComponent",
"counters" => {
"counter1" => "19034",
"counter2" => "90",
"counter3" => "46",
"counter4" => "11",
"counter5" => "0",
"counter6" => "0",
"counter7" => "32737",
},
"host" => "mylinushost",
"@version" => "1"
}

   ruby {
      code => "
          counterdata =  event.get('[counters]')
          counterdata.to_hash
          counterdata.each { |key, value|
              event.set(['counters']['#{key}'], value.to_i)
          }
      "
  }

Please help. Or is there any other option apart from ruby. Thanks

Try

ruby {
    code => '
        event.get("[counters]").each { |key, value|
            event.set("[counters][#{key}]", value.to_i)
        }
    '
}

Hi @Badger,
Thanks.. That worked like a charm.

~Neeraj

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