Serializing an object to JSON

Serializing an object to JSON

How can I serialize an object to JSON in JavaScript?

Solutions/Answers:

Solution 1:

You’re looking for JSON.stringify().

Solution 2:

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

var json_data = JSON.stringify(obj);

Solution 3:

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)
}
Related:  How do I require() from the console using webpack?