简体   繁体   中英

Convert Javascript object to a JSON string

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 json2 library 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).

I think you've totally misunderstood what JSON is. JSON Stands for Javascript Object Notation.

What you haven't realised is that foo is already an object and further have you actually thought about what you'd be coding to access jsonObj ?

Here's a hint jsonObj.test1 : looks familiar doesn't it.

What you might be trying to do is to create a string that looks like JSON content but isn't in fact an object. That's a different question though.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM