til

today i learned

View on GitHub

Printing JSON in the Shell

Printing json might seem straightforward at first, just:

$ echo '{"name": "jes", "sign": "aquarius"}'
# {"name": "jes", "sign": "aquarius"}

but inevitably, variables show up:

$ echo '{"name": "$name", "sign": "$sign"}'
# {"name": "$name", "sign": "$sign"} <-- this output is very broken

We can instead use printf! printf offers several advantages over echo:

Printing the same json text using printf:

$ printf '{"name": "%s", "sign": "%s"}' "$name" "$sign"
# {"name": "jes", "sign": "aquarius"}

source