Search code examples
arraysjsoncounterjsonata

Include Counter in array JSONata


I just started using JSONata and I found it quite fascinating to parse JSON easily. But I have this problem, and I'm not sure if it can be done with JSONata directly.

I want to include a counter that goes from 1 to "the number of objects in an array", like so:

Original output from JSONata expression:

[ { "a": false, "b": "", "c": "", "d": true }, { "a": false, "b": "", "c": "", "d": true }, { "a": false, "b": "", "c": "", "d": true } ]

Wanted output:

[ { "count": "1", "a": false, "b": "", "c": "", "d": true }, { "count": "2", "a": false, "b": "", "c": "", "d": true }, { "count": "3", "a": false, "b": "", "c": "", "d": true } ]

Is it possible? Thank you in advance.


Solution

  • You can use the $map() function to iterate over a list and apply an expression to each item. The second argument of your function will be the index within the array. So for your example, the following will merge the count property into your original array of objects:

    $ ~> $map(function($v, $i) {
      $merge([{'count': $i+1}, $v])
    })
    

    See this working in the JSONata Exerciser: http://try.jsonata.org/rkDpyXMVM