Modify values in json array with Ruby

Hello everyone,

I have a json structure as follows:

{
   "server":[
      {
         "active":true,
         "objID":1
      },
	  {
         "active":true,
         "objID":2
      },
	  {
         "active":false,
         "objID":3
      }
   ]
}

The json structure shows an array of servers and their objID. I would like to create a Ruby filter so that whenever the active field is false, the objID field will be set to an empty string. Below is my Ruby filter however it doesn't work since I am not familiar with Ruby....

a = event.get('[server]')
a.each_index { |i|
if a[i]["active"] == "false"
event.set(a[i]["objID"], "")
end
}

Any help would be appreciated! Thank you in advance.

a[i]["objID"] in event.set(a[i]["objID"], "") may be solved to 3.

Try:

event.set('[server][' + i.to_s + ']["objID"]', "")
1 Like

Thank you for the answer, however when I tried your solution, I still got the syntax error as below:

Ruby {\r\n\t\t             code => \"\r\n\t\t                 a = event.get('[server]')\r\n                     a.each_index { |i|\r\n                        if a[i][\"", backtrace=>["/appl/monitoring/ELK_V7.12.1/logstash-7.12.1/logstash-core/lib/logstash/compiler.rb:32:in `compile_imperative'", "org/logstash/execution/AbstractPipelineExt.java:184:in `initialize'", "org/logstash/execution/JavaBasePipelineExt.java:69:in `initialize'", "/appl/monitoring/ELK_V7.12.1/logstash-7.12.1/logstash-core/lib/logstash/java_pipeline.rb:47:in `initialize'", "/appl/monitoring/ELK_V7.12.1/logstash-7.12.1/logstash-core/lib/logstash/pipeline_action/create.rb:52:in `execute'", "/appl/monitoring/ELK_V7.12.1/logstash-7.12.1/logstash-core/lib/logstash/agent.rb:389:in `block in converge_state'"]}
[2022-06-09T14:24:57,521][INFO ][logstash.runner          ] Logstash shut down.
[2022-06-09T14:24:57,536][FATAL][org.logstash.Logstash    ] Logstash stopped processing because of an error: (SystemExit) exit
org.jruby.exceptions.SystemExit: (SystemExit) exit
        at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:747) ~[jruby-complete-9.2.13.0.jar:?]
        at org.jruby.RubyKernel.exit(org/jruby/RubyKernel.java:710) ~[jruby-complete-9.2.13.0.jar:?]
        at appl.monitoring.ELK_V7_dot_12_dot_1.logstash_minus_7_dot_12_dot_1.lib.bootstrap.environment.<main>(/appl/monitoring/ELK_V7.12.1/logstash-7.12.1/lib/bootstrap/environment.rb:89) ~[?:?]

The left hand side should be a boolean, not a string, so remove the quotes from the right hand side.

1 Like

Thanks everyone! It works now!

1 Like