3

I am trying to use the sum function of JMESPath but having some trouble. I managed to figure out how to use the search function with multiple conditions. This statement:

var x = search(myData, "Account[].Details[? Year=='2018' && Title=='ABC'].Amount");

returns this JSON array:

["2404.00", "2404.00", "2402.67", "2699.00", "2699.00", "2698.49"]

Now what I would like to do is to sum these values. The JMESPath specification says to use this syntax for the built-in sum function:

number sum(array[number] $collection)

I don't understand how to use this function. Can someone please help?

1 Answer 1

2

I'we took your last example and added some more example data, we will sum Prices

const testData =
{
"ServiceAccount": [
    {
        "Type": "WIDGET",
        "ID": [
            {
                "OrderNum": "12345",
                "OrderTyp": "ABDCD",
                "Price": "10",
            }
        ]
      },
      {
        "Type": "WIDGET",
        "ID": [
            {
                "OrderNum": "22345",
                "OrderTyp": "ZBDCD",
                "Price": "20",
            }
        ]
      },
      {
        "Type": "WIDGET",
        "ID": [
            {
                "OrderNum": "22385",
                "OrderTyp": "ZBDXD",
                "Price": "30",
            }
        ]
      }
    ]
};

const result = jmespath.search(testData, 'sum(ServiceAccount[].ID[].Price.to_number(@))');

console.log(result);

   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.min.js"></script>

Answer to your current problem then would be this:

var x = search(myData, "sum(Account[].Details[? Year=='2018' && Title=='ABC'].Amount.to_number(@))");
Sign up to request clarification or add additional context in comments.

3 Comments

Using the testData from this question, how would we sum the Price values, only where the OrderNum is > 20000? I tried using var x = search(myData, "sum(Account[].Details[? OrderNum> 20000].Price.to_number(@))"); but I get this error: Uncaught Error: TypeError: sum() expected argument 1 to be type 8 but received type 3 instead.
@DanielAttard like this: var x = search(myData, "sum(Account[].Details[? OrderNum> 20000].Price | [].to_number(@))")
@DanielAttard i frogot to explain the error, the error is caused because the result is nested list, so you need to use pipe and "Flat operator" to flatten the list and then sum it.

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.