英文:
Not able to parse & return boolean value using jsonpath
问题
{
"translation": "我有一个简单的 JSON(如下所示)。修改后的数组元素中的内容可能会有所不同。每当修改的元素中至少有一个文件名以 'test/' 开头,我都需要有一个固定的输出;如果没有任何文件以 'test/' 开头,则输出不同。我需要使用 JsonPath 来实现这一点。\n\n到目前为止,我使用过的所有表达式(例如 $.commits[].[?(@ =~ /test.*?/i)])都会在匹配表达式时给我文件列表,但我需要有一个固定的值(true 或 false),而不是 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。由于true
和false
不是有效的JSON,因此您无法将它们作为结果返回。您可以获得包含true
或false
的JSON结构,但前提是这些值在原始JSON中存在。
通常做法是获取结果JSON,然后测试它是否符合某些条件。在您的情况下,您期望始终获得一个路径数组。您的条件是“结果列表是否为空?”。因此,您需要测试返回的列表是否为空,以得出您的“固定值”true
或false
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论