jq

The jq utility helps parsing, and modifying JSON structures.

Install

curl \
   --silent \
   --url https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 \
   --location \
   --output ./jq

chmod +x ./jq
sudo mv ./jq /usr/local/bin
sudo chown root.root /usr/local/bin/jq

When I neet to create a larger JSON structure in a shell script, I don't like the approach of creating a honking big string:

#!/bin/bash

someVar1="Something something"
someVar2="something else"

# Create a large JSON string, not very maintainable
json1="{\"v1\":\"${someVar1}\",\"v2\": \"${someVar2}\"}"
echo  "${json1}" | jq .

Instead, I prefer a step-by-step creation process. Below, we're starting with an empty JSON object ("{}"), and piping it through a bunch of jq calls. In such a call, we bind the shell variable's value to the jq variable x, and set the value on the fly:

This outputs

Alternatively, try this:

Which gives

Incrementally adding to an array in JQ

results in

Forgot what I did here...

Crack up the claims part of a JWT

Last updated