TIL: Building JSON Payloads in Shell Scripts With jq
Building JSON in shell scripts with string concatenation always breaks. A missing quote, an unescaped newline, a space in a value. jq builds valid JSON from raw variables.
jq -n --arg model "nova-2" --arg file "$FILENAME" '{model: $model, audio: {url: $file}}'
The –arg flags pass shell variables into jq as string variables. jq handles escaping. The output is always valid JSON.
jq -n --argjson channels 2 '{audio: {channels: $channels}}'
Use –argjson for numbers, booleans, and arrays. jq parses them as native JSON types instead of strings.
AUDIO_FORMAT="wav"
SAMPLE_RATE=16000
jq -n \
--arg format "$AUDIO_FORMAT" \
--argjson rate "$SAMPLE_RATE" \
'{format: $format, encoding: {sample_rate: $rate}}'
Multiple variables compose into complex nested objects. No string interpolation, no escaping bugs.
Does jq handle null values?
Yes. Use –argjson val null to pass a null. Omit the key entirely if the field should not be present.