# How to parse json array to get object count

**URL:** <https://discuss.elastic.co/t/how-to-parse-json-array-to-get-object-count/170409>\
**Category:** Logstash\
**Created:** [February 28, 2019, 9:37pm UTC](https://discuss.elastic.co/t/how-to-parse-json-array-to-get-object-count/170409 "2019-02-28T21:37:19Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [February 28, 2019, 10:35pm UTC](https://discuss.elastic.co/t/how-to-parse-json-array-to-get-object-count/170409/4 "2019-02-28T22:35:11Z")

</div>

Create a file called countObjects.rb that contains this

```auto
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.

---

_[View the full topic](https://discuss.elastic.co/t/how-to-parse-json-array-to-get-object-count/170409)._
