Convert JS object to JSON string

  1. Home
  2. javascript
  3. Convert JS object to JSON string

If I defined an object in JS with:

var j={"name":"binchen"};

How can I convert the object to JSON? The output string should be:

'{"name":"binchen"}'

First answer

All current browsers have native JSON support built in. So as long as you’re not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

Second answer

Check out updated/better way:

Update May 17, 2008: Small sanitizer
added to the toObject-method. Now
toObject() will not eval() the string
if it finds any malicious code in
it.For even more security: Don’t set
the includeFunctions flag to true.

Douglas Crockford, father of the JSON concept, wrote one of the first stringifiers for JavaScript. Later Steve Yen at Trim Path wrote a nice improved version which I have used for some time. It’s my changes to Steve’s version that I’d like to share with you. Basically they stemmed from my wish to make the stringifier:

• handle and restore cyclical references  
• include the JavaScript code for functions/methods (as an option)  
• exclude object members from Object.prototype if needed.

Third answer

You can use JSON.stringify() method to convert JSON object to String.

var j={"name":"binchen"};
JSON.stringify(j)

For reverse process, you can use JSON.parse() method to convert JSON String to JSON Object.

Reprint:https://stackoverflow.com/questions/4162749/convert-js-object-to-json-string
Spread the love

Related articles

Comments are closed.