Home > Enterprise >  How to modify external variable inside jq walk
How to modify external variable inside jq walk

Time:11-22

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!

CodePudding user response:

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
  • Related