I've written a shell function that converts an UTF-8 encoded string to a JSON string, using awk.
json_stringify() {
LANG=C awk '
BEGIN {
for ( i = 1; i < ARGC; i++ )
print json_stringify(ARGV[i])
}
function json_stringify( str, _str, _out ) {
if( ! ("\\" in _ESC_) )
for ( i = 1; i <= 127; i++ )
_ESC_[ sprintf( "%c", i) ] = sprintf( "\\u%04x", i )
_str = str
_out = "\""
while ( match( _str, /[\"\\[:cntrl:]]/ ) ) {
_out = _out substr(_str,1,RSTART-1) _ESC_[substr(_str,RSTART,RLENGTH)]
_str = substr( _str, RSTART + RLENGTH )
}
return _out _str "\""
}
' "$@"
}
It feels like I missed something trivial, because when I run (in bash):
json_stringify 'A"B' 'C\D' $'\b \f \t \r \n'
I get:
"A\u0022B"
while my expected output is:
"A\u0022B"
"C\u005cD"
"\u0008 \u000c \u0009 \u000d \u000a"
What could be the problem(s) in my code?