Last active
March 14, 2019 09:58
-
-
Save gandro/1852afae4539a1b39d330f016707e3bf to your computer and use it in GitHub Desktop.
POSIX shell compliant JSON string escape
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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