Escaping characters in bash (for JSON)

jq can do this.

Lightweight, free, and written in C, jq enjoys widespread community support with over 15k stars on GitHub. I personally find it very speedy and useful in my daily workflow.

Convert string to JSON

echo -n '猫に小判' | jq -Rsa .
# "\u732b\u306b\u5c0f\u5224"

To explain,

  • -R means “raw input”
  • -s means “include linebreaks” (mnemonic: “slurp”)
  • -a means “ascii output” (optional)
  • . means “output the root of the JSON document”

Git + Grep Use Case

To fix the code example given by the OP, simply pipe through jq.

MSG=`git log -n 1 --format=oneline | grep -o ' .\+' | jq -Rsa .`

Leave a Comment