Reputation: 13
I have following JSON object
{"color": "red", "shapes": [ "square", "triangle" ]}
I would like to validate the JSON object using jq using following conditions:
The returned result should be either true or false.
I have 2 jq command which validate both conditions, but I'm not sure how to combine this into 1 expression:
json='{"color": "red", "shapes": [ "square", "triangle" ]}'
echo "$json" | jq '.["color"] | test("red")'
echo "$json" | jq 'any(.shapes[]; contains("round"))|not'
Any pointers or help would be appreciated.
Upvotes: 1
Views: 506
Reputation: 116780
A correct way to test a collection of conditions is using and
.
In your case, a correct test would be:
(.color == "red") and (.shapes|index("round") == null)
Example (typescript):
jq '(.color == "red") and (.shapes|index("round") == null)'
{"color": "red", "shapes": [ "square", "triangle" ]}
true
In jq, not
is a syntactically ordinary filter, so you could write the second condition as: (.shapes | index("round") | not)
.
Upvotes: 2
Reputation: 531345
You can simply verify that both tests return true with all
:
echo '{"color": "red", "shapes": [ "square", "triangle" ]}' |
jq '[(.["color"] | test("red")),
(any(.shapes[]; contains("round"))|not)
] | all'
Create an array containing the results of each test, then pipe that array to all
.
Upvotes: 2