Ruby syntax

How do i write the else if in Ruby. I tried elsif but it didnt work

It is elsif.
Check the LS logs for Ruby Filter exception messages. Perhaps you don't have a syntax error at all - some other error?

input {
  generator {
    message => '{"an_object":{"name":"foo","value":"bar"},"a_number":42,"a_string":"some text","an_array":["foo","bar","baz"],"a_boolean":false}'
    count => 1
  }
}

filter {
  json {
    source => "message"
  }
  if "_jsonparsefailure" not in [tags]  {
    ruby {
      code => '
        event.to_hash.each do |k,v|
          next if k == "@timestamp"
          if v.is_a?(Hash) || v.is_a?(Array)
            event.set(k, v.inspect)
          elsif !v.is_a?(String)
            event.set(k, v.to_s)
          end
        end
      '
    }
  }
}

output {
  stdout {
    codec => rubydebug
  }
}

Gives:

{
      "@version" => "1",
      "an_array" => "[\"foo\", \"bar\", \"baz\"]",
     "an_object" => "{\"value\"=>\"bar\", \"name\"=>\"foo\"}",
       "message" => "{\"an_object\":{\"name\":\"foo\",\"value\":\"bar\"},\"a_number\":42,\"a_string\":\"some text\",\"an_array\":[\"foo\",\"bar\",\"baz\"],\"a_boolean\":false}",
      "sequence" => "0",
    "@timestamp" => 2019-03-12T10:41:52.924Z,
          "host" => "Elastics-MacBook-Pro.local",
      "a_string" => "some text",
     "a_boolean" => "false",
      "a_number" => "42"
}

oh so the elsif doesn't need an independent end
i was using :
if expression
code
end
elsif expression
code
end
else
end

Exactly.
it is

if <condition>
  <code>
elsif <condition>
  <code>
elsif <condition>
 <code>
else
  <code>
end

with as many elsif <condition> as needed.

thank you so much!

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