How to parse json array to get object count

Create a file called countObjects.rb that contains this

def register(params)
    @field = params['field']
    @target = params['target']
end

def countObjects(object)
    c = 0
    if object
        c = 1
        if object.kind_of?(Array)
            object.each { |x| c += countObjects(x) }
        elsif object.kind_of?(Hash)
            object.each { |k, v| c += countObjects(v) }
        end
    end
    c
end

def filter(event)
    event.set(@target, countObjects(event.get(@field)))
    [event]
end

You can call it using

    ruby {
        path => "/home/user/countObjects.rb"
        script_params => { "field" => "someField" "target" => "count" }
    }

which will count the number of object in someField and add a count field to the event that contains the number.

1 Like