amazon-web-servicesaws-step-functionsjsonata

Aggregating stats in Json nata - i.e. in Step Functions Map


I have spent an embarrassing amount of time trying to achieve something that I believe should be quite trivial.

The question is about JSONata because I want to use this in the context of an AWS Step Function.

Let's say I have an array with some stats, each coming, say, from the execution of a separate process. In my real case, it will come from a Map Step.

Importantly, I do not know which stats are coming in; I do not have a pre established list of possible stat keys.

[{
    "stat1": 2,
    "stat2": 3 
},
{
    "stat1": 4,
    "stat3": 5
}]

I would like to use JSONata to aggregate those, so that each different stat is aggregated using sum, to basically obtain something like this:

{
    "stat1": 6,
    "stat2": 3,
    "stat3": 5
}

Solution

  • Does this work?

    $spread(){ $keys($): $sum($.*) }

    First, it splits all objects's keys into separate arrays, then groups them based on the key and aggregates the values.

    JSONata Playground: https://jsonatastudio.com/playground/8a13fa7e