Skip to content

Instantly share code, notes, and snippets.

@gandro
Last active March 14, 2019 09:58
Show Gist options
  • Save gandro/1852afae4539a1b39d330f016707e3bf to your computer and use it in GitHub Desktop.
Save gandro/1852afae4539a1b39d330f016707e3bf to your computer and use it in GitHub Desktop.
POSIX shell compliant JSON string escape
json_escape() {
printf '"'
for oct in $(printf '%s' "$1" | od -A n -t o1) ; do
case $oct in
010) printf '\\b' ;;
011) printf '\\t' ;;
012) printf '\\n' ;;
014) printf '\\f' ;;
015) printf '\\r' ;;
042) printf '\\"' ;;
134) printf '\\\\' ;;
00?) printf '\\u%04x' $oct ;;
01?) printf '\\u%04x' $oct ;;
02?) printf '\\u%04x' $oct ;;
03?) printf '\\u%04x' $oct ;;
???) printf "\\$oct" ;;
esac
done
printf '"'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment