How to validate a json value is numeric

noob question

I have a JSON as follows:
{"attr1":"One", "attr2":"300"}
{"attr1":"Two","attr2":45.0}
{"attr1":"Three","attr2":"Not Set"}

attr2 is a numeric value

How do I check if attr2 is numeric, not a string before sending to elastic ?
I can check easily for the "Not Set"
if [attr2] == "Not Set"
{ drop { remove_field => [ "attr2" ] } }

but
ie. If attr is a string and is a numeric string then
convert to a number value

If it is a numeric string you can use

 mutate { convert => { "attr2" => float } }

This will convert "Not set" to 0.0, so do the drop before the mutate.

So any value that is not valid will transform to 0.0 ?
Is there a way to check for the non-numeric value (in case another string value gets added) ?
Rather have a NULL value than a 0.0 value

Thanks

You could do it in ruby

    ruby {
        init => '
            def is_numeric? s
                true if Float(s) rescue false
            end
        '
        code => '
            s = event.get("attr2")
            unless is_numeric? event.get("attr2") ; event.remove("attr2") ; end
        '
    }
1 Like

Thank you

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