在使用 jq 验证 JSON 内容时结合多个测试
Combining multiple tests in validating JSON content with jq
我有以下 JSON 个对象
{"color": "red", "shapes": [ "square", "triangle" ]}
我想使用 jq 使用以下条件验证 JSON 对象:
- 颜色 具有值 "red"
- shapes 不包含值 "round"
返回结果应为true或false。
我有 2 个 jq 命令来验证这两个条件,但我不确定如何将其组合成 1 个表达式:
json='{"color": "red", "shapes": [ "square", "triangle" ]}'
echo "$json" | jq '.["color"] | test("red")'
echo "$json" | jq 'any(.shapes[]; contains("round"))|not'
如有任何指点或帮助,我们将不胜感激。
您可以通过 all
:
简单地验证两个测试 return 是否正确
echo '{"color": "red", "shapes": [ "square", "triangle" ]}' |
jq '[(.["color"] | test("red")),
(any(.shapes[]; contains("round"))|not)
] | all'
创建一个包含每个测试结果的数组,然后将该数组传送到 all
。
测试条件集合的正确方法是使用 and
。
对于您的情况,正确的测试是:
(.color == "red") and (.shapes|index("round") == null)
示例(打字稿):
jq '(.color == "red") and (.shapes|index("round") == null)'
{"color": "red", "shapes": [ "square", "triangle" ]}
true
在jq中,not
是语法上普通的过滤器,所以第二个条件可以写成:(.shapes | index("round") | not)
.
我有以下 JSON 个对象
{"color": "red", "shapes": [ "square", "triangle" ]}
我想使用 jq 使用以下条件验证 JSON 对象:
- 颜色 具有值 "red"
- shapes 不包含值 "round"
返回结果应为true或false。
我有 2 个 jq 命令来验证这两个条件,但我不确定如何将其组合成 1 个表达式:
json='{"color": "red", "shapes": [ "square", "triangle" ]}'
echo "$json" | jq '.["color"] | test("red")'
echo "$json" | jq 'any(.shapes[]; contains("round"))|not'
如有任何指点或帮助,我们将不胜感激。
您可以通过 all
:
echo '{"color": "red", "shapes": [ "square", "triangle" ]}' |
jq '[(.["color"] | test("red")),
(any(.shapes[]; contains("round"))|not)
] | all'
创建一个包含每个测试结果的数组,然后将该数组传送到 all
。
测试条件集合的正确方法是使用 and
。
对于您的情况,正确的测试是:
(.color == "red") and (.shapes|index("round") == null)
示例(打字稿):
jq '(.color == "red") and (.shapes|index("round") == null)'
{"color": "red", "shapes": [ "square", "triangle" ]}
true
在jq中,not
是语法上普通的过滤器,所以第二个条件可以写成:(.shapes | index("round") | not)
.