On , I learnt ...

You can use JQ to build JSON payloads

It’s possible to use JQ to build JSON payloads as well as filter them.

This is useful when constructing dynamic JSON payloads at the CLI as JQ will escape input variables correctly.

Simple example:

$ jq -n --arg name "Alan" '{name: $name}'
{
  "name": "Alan"
}

The -n (--null-input) option tells JQ not to read any input.

Values passed with --arg will always serialise as strings:

$ jq -n --arg name "Alan" --arg age 20 '{name: $name, age: $age}'
{
  "name": "Alan",
  "age": "20"
}

To serialize other types, use --argjson:

$ jq -n --arg name "Alan" --argjson age 20 '{name: $name, age: $age}'
{
  "name": "Alan",
  "age": 20
}

Using JQ in this way is useful for making HTTP requests as the dynamic JSON payload can be piped into http:

$ jq -n --arg name "Alan" --argjson age 20 '{name: $name, age: $age}' \
    | http https://example.com/api/users/register/

See my post on using OpenAI to convert commit messages into poems for a more complete example.