如何使用 JSONPath 表达式从 JSON 对象数组中提取值

问题描述 投票:0回答:1

我有 JSON 格式的数据,它看起来像这样:

{
    "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
    }]
}

我只想以数组的形式提取与“book”内每个对象相对应的值。

我的输出应该是这样的:

[ “参考”, “奈杰尔·里斯”, 《世纪名言》、 8.95 ], [ “小说”, “伊芙琳·沃”, 《荣誉之剑》, 12.99 ]

有没有办法使用 JSONPath 表达式来做类似的事情

$.book[*].[作者、类别、书名、价格]

javascript arrays transformation jsonpath json-path-expression
1个回答
0
投票

只映射每个对象的值?

const data = {
  "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
  }]
};

const extractedValues = data.book.map(Object.values);

console.log(extractedValues);
.as-console-wrapper { top: 0; max-height: 100% !important; }
["reference", "Nigel Rees", "Sayings of the Century", 8.95],
["fiction", "Evelyn Waugh", "Sword of Honour", 12.99]

© www.soinside.com 2019 - 2024. All rights reserved.