【问题标题】:Unable to fetch the specific element value using jsonpath node js library无法使用 jsonpath 节点 js 库获取特定元素值
【发布时间】:2021-07-01 06:05:08
【问题描述】:

我正在尝试根据复杂 JSON 文件中的值获取元素的值。

如果 currency ='BRL'索引会发生变化,则尝试获取 value 属性(即 100),所以我只想尝试基于条件。

到目前为止,我只是在下面尝试过:

脚本:

function test()
{
   var result = jsonpath.query(payload,"$..client_balance[?(@.type == 'AVAILABLE')]");
   console.log(result);
}

test();

输出:

[
  {
    amount: { currency: 'BRL', value: '100', skip: false },
    type: 'AVAILABLE'
  },
  {
    amount: { currency: 'USD', value: '10', skip: false },
    type: 'AVAILABLE'
  }
]

现在,如果 currency code = 'BRL',我只想获取 value 属性(即 100)。我尝试应用 [?(@.currency == 'BRL')] 在路径变量的尾部,但它返回空数组。

谁能帮我解决这个问题。

更新:

尝试了过滤函数来获取特定元素的值。

console.log(Object.values(payload).filter(element =>{
    element.currency === 'BRL';
   }));

输出:

[]

【问题讨论】:

  • 你试过用双等号[?(@.currency == 'BRL')] 吗?
  • 是的。我试过了,它返回空数组。
  • 对不起。我认为应该是[?(@.amount.currency == 'BRL')]
  • @Andy - 我尝试使用下面的代码使用过滤器将货币代码的值获取到 BRL,但它不起作用。由于有效负载更复杂,并且它包含嵌套数组。所以想选择 jsonpath 方法。使用过滤函数结果更新问题。

标签: node.js jsonpath


【解决方案1】:
console.log(Object.values(payload).filter(element =>{
   return element.amount.currency === 'BRL';
}));

我认为这应该可行

【讨论】:

  • 它返回以下错误。根本原因 JSON 文件比较复杂,它需要使用 jsonpath 从根元素开始。 TypeError:无法读取 C:\Users\arrcana\Documents\folder**\Test.js:11:27 at Array.filter () 处未定义的属性“货币”在测试 (C:\Users\arrchana\ Documents\folder**\Test.js:10:39) 在 Object. (C:\Users\arrcana\Documents\folder**\Test.js:16:1)
  • 可能有少数项目根本没有数量对象。在这种情况下,您可以尝试 return (element.amount && element.amount.currency === 'BRL');
  • 让我看看这个..!
【解决方案2】:

这是一个有点复杂的查询,但它应该会为您提供所需的内容。

从你所拥有的开始,它会返回你发布的结果集:

$..client_balance[?(@.type == 'AVAILABLE')]

添加另一个过滤器,在currency 字段的amount 字段内进行比较:

$..client_balance[?(@.type == 'AVAILABLE')][?(@.amount.currency === 'BRL')]

这应该只给出一个元素:

[
  {
    amount: { currency: 'BRL', value: '100', skip: false },
    type: 'AVAILABLE'
  }
]

您想从这里获取value 字段,但要到达那里,您需要它的路径,这意味着您必须先通过amountcurrency 字段。

$..client_balance[?(@.type == 'AVAILABLE')][?(@.amount.currency === 'BRL')].amount.currency.value

这应该返回

[
  100
]

请注意,我们是working on a specification for JSON Path。如果此库在发布后选择遵守它,=== 将需要更改为 ==,因为这就是我们的 decided to support

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    相关资源
    最近更新 更多