【问题标题】:Sum of array in jsonpathjsonpath中数组的总和
【发布时间】:2020-10-13 19:19:41
【问题描述】:

我正在尝试使用 sum() 函数。我已经浏览了Functions min(), max() or sum() with jsonpath 链接,但这并不能帮助我解决问题。我试图在https://jsonpath.herokuapp.com/ 上运行表达式,这给了我 $..price 的结果,其中包含年龄数组,但是当我想要像 $..price 这样的年龄总和时。 sum() 这给了我一个错误聚合函数试图使用空数组计算值。请你帮我写下正则表达式以获得年龄的总和。

【问题讨论】:

  • 我们应该如何帮助您针对我们看不到的 json 文件编写 jsonpath 表达式???
  • @tomredfern 我已经给出了 json 的 URL,你可以在同一个 URL 上尝试这个表达式。
  • 对于反对的选民,你能解释一下为什么这个问题不好吗?

标签: javascript arrays sum jsonpath


【解决方案1】:

安装包: https://www.npmjs.com/package/jsonpath

然后使用method reduce,试试:

var jp = require('jsonpath');

var data = {
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

let sum = jp.query( data , '$..price' ).reduce( (acc,ele) => acc += ele ,0);

console.log(sum);

【讨论】:

  • 感谢您的回答,但我正在寻找可以帮助我利用 sum() 方法的正则表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2018-03-06
  • 2018-09-16
  • 2015-12-16
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多