Serializing an object to JSON

JavascriptJson

Javascript Problem Overview


How can I serialize an object to JSON in JavaScript?

Javascript Solutions


Solution 1 - Javascript

You're looking for JSON.stringify().

Solution 2 - Javascript

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

Solution 3 - Javascript

Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):

function winHasJSON(){
  json_data = JSON.stringify(obj);
  // ... (do stuff with json_data)
}
if(typeof JSON === 'object' && typeof JSON.stringify === 'function'){
  winHasJSON();
} else {
  $.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmaxaposterioriView Question on Stackoverflow
Solution 1 - JavascriptMike_GView Answer on Stackoverflow
Solution 2 - JavascriptJohannes WeissView Answer on Stackoverflow
Solution 3 - JavascriptAvLView Answer on Stackoverflow