I want to directly convert a javascript object to string. I used following code.
var foo = {};
foo.test1 = test1;
foo.test2 = test2;
foo.test3 = test3;
var jsonObj = JSON.stringify(foo);
It works fine but it uses the json2 javascript library. However I need to do this in plain javascript without using any libraries. I know creating the json feed using passed parameters will work like this.
var jsonObj = "{\"test1\":\"" + test1+ "\",\"test2\":\"" + test2+ "\",\"test3\":\"" + test3+ "\"}";
However if the passed parameters(test1, test2 and test3) contains double quotes it will have issues.
What is the best approach to achieve this?
Thank you
You should escape the double quotes by performing a
String.replace(/"/g, "\\\"")on each key and member. For this to work however, you need to guarantee that you will only have simple strings/ numbers in your JS object.FYI, it should be noted that the
json2library will only be used when a native implementation of JSON does not exist; all modern browsers have JSON support build in (IE < 8 is the noticable exception).