JSON.stringify With Escape For Unicode-Characters

Posted at

You may be familiar with PHP's json_encode which allows you to do wonderful things such as giving you a ASCII safe version of Unicode-content (which is the default, and if you actually do want to return a plain Unicode content you need to specify JSON_UNESCAPED_UNICODE flag).


In your browser (or NodeJS in that matter..) JSON.stringify do not include a built-in parser for you to use, but it DOES include an option to specify a "replacer" function, which acts as the parser, naturally there is a lot more free-ground to play around, but if the only thing you need is something similar to PHP's json_encode read ahead..



A nifty little trick I'm going to use next is a regular-expression replacing using Unicode values of all characters with code above 160 (decimal) to the maximum value for a single Unicode-character which is 65535.
Although we can tolerate character-values of up until 255, those above 160 are generally not-considered ASCII safe, and includes special control-characters and language-directional control which might break the text-stream.






Happy escaping! :)