DEV Community

JL
JL

Posted on

jq - Json Query Tool in bash

Cheatsheet (with explanation on what the params do):
https://stedolan.github.io/jq/manual/

Common Operations

Iterate all elements (and override some) within a JSON object


          echo $temp > json-override.json

          for key in $(jq '. | keys' json-override.json); do

              # remove starting and trailing quotes
              ref_key=`echo $key | tr -d '"'`
              ref_key=`echo $ref_key | tr -d ','`
              if [ $key != '[' ] && [ $key != ']' ]
              then
                  ref_val=`jq \
                  --arg target_key $ref_key \
                  '.[$target_key]' json-override.json`
                  ref_val=`echo $ref_val | tr -d '"'`
                  # echo $ref_key = $ref_val

                  case $ref_val in
                    OLD VALUE)
                      ref_val='NEW VALUE'
                      ;;
                    *)
                      echo -n "Unknown secret"
                      exit 1
                      ;;
                  esac

                  temp=`echo $temp | \
                  jq \
                  --arg target_key $ref_key \
                  --arg target_val "$ref_val" \
                  '.[$target_key] |= $target_val'`
              fi
          done
          echo $temp
Enter fullscreen mode Exit fullscreen mode

Top comments (0)