Json parse return filled with NULL

I parse JSON, and even If JSON is invalid I want to save it.
So I created an additional variable "invalid". If there is an exception, the method should return "saved" invalid var, but it doesn't -

def jsonParse(str, ev)
    invalid = str
begin
    parsed = JSON.parse(str)
rescue => e
    ev.tag("_parseJsonFail")
    return invalid
end
return parsed
end

I run code with ruby filter plugin (code option):

#...some parse magic.....
#
jsmap.each_pair {|key, value| event.set("#{key}", jsonParse(value, event)) }

If i feed pipeline with invalid JSON - fields after event.set filled by "null":

image

But tagged:

image

What I do wrong with return op?

I do not see anything wrong with that. This gets me "a" => "foo"

        code => '
            def jsonParse(str, ev)
                invalid = str
                begin
                    parsed = JSON.parse(str)
                rescue => e
                    ev.tag("_parseJsonFail")
                    return invalid
                end
                return parsed
            end
            event.set("a", jsonParse("foo", event))
        '

What is cc set to in the input?

Yep, please try to parse invalid JSON, similar like this:
'["123":123]'

event.set("a", jsonParse("[\"123\":123]", event))

gets me "a" => "["123":123]" with a "_parseJsonFail" tag.

I have created for additional "debug level" this method:

def jsonParse(str, ev)
    invalid = str
    if invalid then
    ev.set("X1",invalid)
else
    ev.set("X2-invalid",invalid)
    end
    begin
        parsed = JSON.parse(str)
    rescue => e
        ev.tag("_parseJsonFail")
        ev.set("X3",parsed)
        ev.set("X4",invalid)
        return invalid
    end
    return parsed
end

image
X1 doesnt exist :smiley:
Is it a curse? :smiley:

The evidence very much suggests you are calling

event.set("cc", jsonParse(nil, event))

yep, but it doesn't work only when I call invalid JSON
when valid - parsing Ok
image

maybe I have a misunderstanding?
invalid JSON:
'["abc" : 123]' == nil
?

But [ "vasya@example.com", "valera@example.com" ] is an example of invalid JSON. It requires {} around it to be parseable.

I checked code by the:



is it wrong?

@Badger Thanks a lot you were right!!
When i pass to logs:
{"aaa":"123"}
It breaks
So it should be passed (with spaces):
{"aaa" : "123"}
magic! Need some time to solve it :slight_smile:
Anyway, shake your hand! Thanks for your help!

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