2

我正在尝试使用的sum功能,JMESPath但遇到了一些麻烦。我设法弄清楚如何在多个条件下使用搜索功能。这个说法:

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

返回此 JSON 数组:

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

现在我想做的是对这些值求和。JMESPath规范说对内置sum函数使用这种语法:

number sum(array[number] $collection)

我不明白如何使用这个功能。有人可以帮忙吗?

4

1 回答 1

1

我拿了你的最后一个例子并添加了更多的示例数据,我们将总结价格

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>

您当前的问题的答案是这样的:

var x = search(myData, "sum(Account[].Details[? Year=='2018' && Title=='ABC'].Amount.to_number(@))");
于 2018-08-11T06:46:01.353 回答