From 951e9d066c92326d6c8aa49d1b26c32559f715b5 Mon Sep 17 00:00:00 2001 From: byt3h3ad Date: Sun, 8 Oct 2023 02:35:19 +0530 Subject: [PATCH] new file: shell/printing-json.md --- shell/printing-json.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 shell/printing-json.md diff --git a/shell/printing-json.md b/shell/printing-json.md new file mode 100644 index 0000000..b130f6c --- /dev/null +++ b/shell/printing-json.md @@ -0,0 +1,31 @@ +# Printing JSON in the Shell + +Printing json might seem straightforward at first, just: + +```shell +$ echo '{"name": "jes", "sign": "aquarius"}' +# {"name": "jes", "sign": "aquarius"} +``` + +but inevitably, variables show up: + +```shell +$ 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: + +- many languages (C, Go) have a `printf` equivalent, so it feels familiar +- `printf` behavior does not differ across systems (it is posix compliant) +- `printf` handles escape sequences (`printf "hello\nworld\n"`) +- `printf` can trivially handle json + +Printing the same json text using `printf`: + +```shell +$ printf '{"name": "%s", "sign": "%s"}' "$name" "$sign" +# {"name": "jes", "sign": "aquarius"} +``` + +[source](https://j3s.sh/thought/shell-tip-print-json-with-printf.html)