How to convert a value to JSON string

jsonI’m working on a project where we use JSON arrays to send data to an API via JavaScript code, but we need to be sure that the data that we are sending is correctly encoded. Specially, with characters like: \, @, double quote, etc.

I found some alternatives, like the escape() function, but at the end, a friend suggested me that we should use JSON.stringify() instead, since we are working with JSON, and was the perfect solution!!.

Here is an example of how you can use JSON.stringify() using jQuery Ajax:

var strData = "{'content' :" + JSON.stringify(txtComment) + "}";

$j.ajax({
	url : url,
    type : "POST",
    async : false,
    data : strData,
    contentType : "application/json",
    statusCode : {
    	200 : function() {
            console.log("added");
       	}
    }
});

Note: console.log can throw errors in IE, they are there for illustrative purposes only and should be changed as required.

So, sending a text like: “This” is a message, using the previous code, the text will be converted as:

{'content' :"\"this\" is a message"}

And now it can be correctly interpreted by the API.

I really hope you find this information useful.