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 you get the logical xor of two variables in Python?
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
Related Topics
Using a SQL Server for Application Logging. Pros/Cons
MySQL Join Two Tables Count and Sum from Second Table
Help Me Put Oracle Terminology into SQL Server Terminology
Check If a Variable Is Null in Plsql
Ruby Activerecord and SQL Tuple Support
How to Generate SQL from Dbplyr Without a Database Connection
Insert and Update a Record Using Cursors in Oracle
What Does "Where 1" Mean in Sql
How to Get Column Names from a Query in SQL Server
Running Total by Group SQL (Oracle)
Insert-Output Including Column from Other Table
Sql Query to Sum Fields from Different Tables
How to Optimize Tables for Specific Queries
How to Use Isnull to All Column Names in SQL Server 2008
Parsing Nested Xml into SQL Table
Activerecord::Statementinvalid. Pg Error
Use a Like Statement on SQL Server Xml Datatype
Using with VS Declare a Temporary Table: Performance/Difference