Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify external variable inside jq walk

I’m currently writing a script that uses the function walk in jq, which I’m using to check for the value of a field, which can appear multiple times in the file. If any instance of that field is not true, I want to echo an error notifying users that the field is invalid. Similar to below:

flag=false

cat file.json | jq 'walk (
  if type == "object" and has "foo" and (.foo != true); then
     flag=true
  else . end
)'

if [[ "$flag" == true ]]; then
  echo "ERROR"
  exit 1
fi

How can I notify the rest of the program if the check inside walk fails ? Any help is much appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Wouldn’t using all and the --exit-status (or -e) option make more sense here?

if jq -e 'all(.. | objects | select(has("foo")); .foo)' file.json >/dev/null
then
  echo "All true"
else
  echo "At least one not true"
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading