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?
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(@))");