How to escape a JSON string containing newline characters using JavaScript?
Take your JSON and .stringify()
it. Then use the .replace()
method and replace all occurrences of \n
with \\n
.
EDIT:
As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace()
method and replace all of the special characters like this:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server.
But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace()
calls. So let's put that functionality into a function called, escapeSpecialChars()
. Let's go ahead and attach it to the prototype chain
of the String
object, so we can call escapeSpecialChars()
directly on String objects.
Like so:
String.prototype.escapeSpecialChars = function() {
return this.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
};
Once we have defined that function, the main body of our code is as simple as this:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server
How do I handle newlines in JSON?
This is what you want:
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
You need to escape the \
in your string (turning it into a double-\
), otherwise it will become a newline in the JSON source, not the JSON data.
JS escape newlines in JSON
Why are you building a JSON string by hand? Why not use JSON.stringify and have the library handle escaping for you?
newissuesjsonstring = JSON.stringify({
newissuetype: $(newissuehtml).find('.newissuetypeinput').val(),
newissueguid: $(newissuehtml).find(".issueguid").val(),
newissuedetails: $(newissuehtml).find('.newissuedetailsinput').val(), //no need for manual escaping!
/*...*/
});
JSON.parse with newline
JSON.parse('{"x": "\n"}')
fails because '{"x": "\n"}'
is not a valid JSON string due to the unescaped slash symbol.
JSON.parse()
requires a valid JSON string to work.
'{"x": "\\n"}'
is a valid JSON string as the slash is now escaped, so JSON.parse('{"x": "\\n"}')
will work.
JSON.parse(JSON.stringify({"x" : "\n"}))
works because JSON.stringify internally escapes the slash character.
The result of JSON.stringify({"x" : "\n"})
is {"x":"\n"}
but if you try to parse this using JSON.parse('{"x":"\n"})'
it will FAIL, as it is not escaped. As JSON.stringify returns an escaped character, JSON.parse(JSON.stringify())
will work.
Related Topics
What Does "Options = Options || {}" Mean in JavaScript
When You Pass 'This' as an Argument
Is Safari on iOS 6 Caching $.Ajax Results
Read Environment Variables in Node.Js
In JavaScript, Why Is "0" Equal to False, But When Tested by 'If' It Is Not False by Itself
How to Resize Images Proportionally/Keeping the Aspect Ratio
Add Directives from Directive in Angularjs
How to Get the File Name from a Full Path Using JavaScript
How to Focus on a <Div> Using JavaScript Focus() Function
How to Find Prime Numbers Between 0 - 100
Sort Array by Firstname (Alphabetically) in JavaScript
Asynchronously Load Images with Jquery
How to Listen to a "Style Change" Event
Primitive Value VS Reference Value
How to Perform a Dns Lookup (Hostname to Ip Address) Using Client-Side JavaScript