1

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
}

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure but I am thinking >>>

(
  $keys := $distinct($.*.$keys());
  $reduce($keys, {}, function($result, $key) {
    $result{$key} := $sum($.[*][$key]);
    $result
  })
)

It just gets all unique keys first, then adds up the value for each key across all objects no need to know the stat names beforehand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.