Pass NULL argument with JQ --arg

Viewed 669

My desired end state is a JSON file like this:

{
   "xxx": null
}

but the command jq --null-input --arg tst null '.xxx=$tst' produces:

{
  "xxx": "null"
}

and jq --null-input --arg tst "" '.xxx=$tst' produces:

{
  "xxx": ""
}

How can I pass a value that becomes the value null and not string "null"?

2 Answers

Use --argjson, not --arg.

$ jq --null-input --argjson tst null '.xxx=$tst'
{
  "xxx": null
}

--arg always treats the assigned value as a string, while --argjson treats it as a JSON value.

Three other simple possibilities, shortest first:

jq -n '{xxx: .}'
echo null | jq  '{xxx: .}'
jq -n --argjson xxx null  '{$xxx}'
Related