Peter Rehm's Blog

apple,development,life & more

Escape special characters within JSON.stringify

Mit 2 Kommentaren

In order to stringify an Object to a JSON string you have to escape the special characters.
Specials characters are for example the following:

CODE:
\b  Backspace (ascii code 08)
\f  Form feed (ascii code 0C)
\n  New line
\r  Carriage return
      Tab
\v  Vertical tab
'  Apostrophe or single quote
"  Double quote
\  Backslash caracter
& Ampersand


Unfortunately JSON.stringify() is not taking care of the special characters. However you can
easily convert those characters with a replacer function within JSON.stringify().

The method to handle such characters looks as follows:

QUOTE:

// escape json strings
function escapeSpecialCharacters(string)
{
return string
.replace(/[']/g, "\\'")
.replace(/["]/g, '\\"')
.replace(/[&]/g, "\\&")
.replace(/[\n]/g, "\\n")
.replace(/[\r]/g, "\\r")
.replace(/[\t]/g, "\\t")
.replace(/[\b]/g, "\\b")
.replace(/[\v]/g, "\\v")
.replace(/[\f]/g, "\\f");
}

// replacer handler for JSON stringify
function stringifyReplacer(key, value)
{
if (typeof value === 'string') {
return escapeSpecialCharacters(value);
}

return value;
}


Now you only have to pass the function name "stringifyReplacer" to the stringify Method.

CODE:
var object = { 'asd' : 'as\nd' };
var json = JSON.stringify(object, stringifyReplacer);


Now you should have an valid JSON string which you can parse again with JSON.parse().

Always escaping whenever you stringify a object to JSON is a good idea to keep you application
working even when special characters are being provided.

Geschrieben von Peter Rehm

07.10.2014 um 19:11:34

Abgelegt in Programmierung

Tags für diesen Artikel: ,