如何使用 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”内每个对象相对应的值。

我的输出应该是这样的:

[
    "reference",
    "Nigel Rees",
    "Sayings of the Century",
    8.95
],
[
    "fiction",
    "Evelyn Waugh",
    "Sword of Honour",
    12.99
]

有没有办法使用 JSONPath 表达式来做这样的事情。

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; }

如果你想保证顺序,你可以提供一个键数组:

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 extractValues = (arr, ...keys) => arr.map(obj => keys.map(key => obj[key]));

const extractedValues = extractValues(data.book, 'category', 'author', 'title', 'price');

console.log(extractedValues);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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