Building JSON with printf and "%s" gives broken JSON as soon as the text contains a quote, a backslash or a tab. jq then stops at the first unexpected spot.
Symptom
text='Er sagte "hallo" und ging\ – mit Tab: Ende'
printf '{"text":"%s"}\n' "$text" | jq . 2>&1 | head -1
jq: parse error: Invalid numeric literal at line 1, column 25
The quote before hallo ends the JSON string early.
Diagnosis
The same built with jq – the result is valid JSON.
jq -n --arg t "$text" '{text: $t}'
{
"text": "Er sagte \"hallo\" und ging\\ – mit Tab:\tEnde"
}
Causes
column 25Unescaped quotes
printf inserts the text raw. " ends the string, after that jq sees a word that is neither a number nor a valid token.
Fix
Always build JSON with jq: --arg for text, --argjson for numbers, true/false and lists.
jq -nc --arg t "$text" --argjson prio 2 '{text: $t, prio: $prio, tags: ["a", "b"]}'
{"text":"Er sagte \"hallo\" und ging\\ – mit Tab:\tEnde","prio":2,"tags":["a","b"]}
Don't: Escape quotes yourself with sed. You will forget backslashes, tabs and control characters.
▶
Break it yourself and find it – free
Shell scripting hands-on, Day 8: curl and jq – query and feed APIs safely from the shell.
Go to day 8 →
Shell scripting hands-on, Day 8: curl and jq – query and feed APIs safely from the shell.
Go to day 8 →
FAQ
What is the difference between --arg and --argjson?
--arg always passes a string, --argjson real JSON such as numbers, true or lists.
What is -r for?
-r prints text without JSON quotes – required when the result goes into a shell variable or to grep.