无法使用 JSONPath 解析和返回布尔值

huangapple go评论59阅读模式
英文:

Not able to parse & return boolean value using jsonpath

问题

{
"translation": "我有一个简单的 JSON(如下所示)。修改后的数组元素中的内容可能会有所不同。每当修改的元素中至少有一个文件名以 'test/' 开头,我都需要有一个固定的输出;如果没有任何文件以 'test/' 开头,则输出不同。我需要使用 JsonPath 来实现这一点。\n\n到目前为止,我使用过的所有表达式(例如 $.commits[].[?(@ =~ /test.*?/i)])都会在匹配表达式时给我文件列表,但我需要有一个固定的值(truefalse),而不是 modified[] 元素的值,只要修改元素中的任何数组元素以 'test' 开头。\n\n如果能提供任何帮助,将不胜感激。\n\n\n {"commits":[{"modified":["test/db/ecs-db.sql","test/infra/infra-settings.json","test1/code/code.java"]}]}"
}

英文:

I have a simple JSON(below). The content in the modified array element may vary. I need to have a fixed output whenever the modified element has at least one file name that starts with 'test/' and a different output if none of the file starts with 'test/'. I need to do that using JsonPath.

So far all the expressions I have used (e.g. $.commits[].[?(@ =~ /test.*?/i)]) gives me the list of files if the expression is matched, I need to have a fixed value (true or false) not the modified[] element value, if any of the array element in the modified element starts with 'test'.

Any help will be much appreciated.

{"commits":[{"modified":["test/db/ecs-db.sql","test/infra/infra-settings.json","test1/code/code.java"]}]}

答案1

得分: 1

JSONPath的定义是:

JSONPath定义了用于遍历JSON文档以提取JSON子集的表达式。

你可以获得的只是“原始JSON的子集”。JSONPath的结果始终是JSON。由于truefalse不是有效的JSON,因此您无法将它们作为结果返回。您可以获得包含truefalse的JSON结构,但前提是这些值在原始JSON中存在。

通常做法是获取结果JSON,然后测试它是否符合某些条件。在您的情况下,您期望始终获得一个路径数组。您的条件是“结果列表是否为空?”。因此,您需要测试返回的列表是否为空,以得出您的“固定值”truefalse

英文:

The definition of JSONPath is:

> JSONPath defines expressions to traverse through a JSON document to
> extract a subset of the JSON

All you can get back is "a subset of the original JSON". The result of a JSONPath is always JSON. Since true and false are not valid JSON, you can't get either of them back as a result. You could get back a JSON structure containing true or false, but only if those values were in the original JSON.

What is normally done here is that you get back the resulting JSON, and then you test that to determine if it matches some criteria or not. In your case, you expect to always get back an array of paths. Your criteria is "is the resulting list empty?". So you need to test if the list you get back is empty or not to arrive at your "fixed value" of true or false.

huangapple
  • 本文由 发表于 2020年9月8日 07:27:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定