0

I'm trying to write a bash function that would parse a json response and assert if an array of objects all satisfy some condition, but I'm getting nowhere with testing that state.

Exemplary JSON after initial transformations:

[
  {
    "key": "Org1",
    "value": true
  },
  {
    "key": "Org2",
    "value": false
  }
]

The condition is to have all elements (no matter the length of the array) to have value == true.

I'm doing the JSON transformations using jq, but I have no idea how to either store the result in a bash var so I could loop throw the elements or reduce the array to a single value that I could parse directly in an if statement.

Could anyone help?

1
  • 1
    echo "$json" | jq 'all(.value)' tests the value property of each object in the array are true. Commented Oct 28, 2020 at 17:10

1 Answer 1

2

You can use the all function to reduce an array of Booleans* to true if all the Booleans are true. jq will output that value, which you can capture using command substitution.

result=$(jq 'map(.value) | all' tmp.json)

You may not need the actual output, though. It may be sufficient to use the --exit-status option (short form -e) to test if jq would return true or not.

if jq -e 'map(.value) | all' tmp.json > /dev/null; then
   echo "All were true"
else
   echo "At least one was false"
fi

* Among other things; see @peak's comment below

Sign up to request clarification or add additional context in comments.

2 Comments

Technically, and the documentation notwithstanding, the all family of filters uses truthiness rather than true as the criterion. Consider e.g. all(1;.) #=> true ; all(nan;.) #=> true ; all(empty;.) #=> true ; all(null;.) #=> false ;
Holy cow, I did not see this all function. Thank you very much for that one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.