Serializing an object to JSON

Serializing an object to JSON

How can I serialize an object to JSON in JavaScript?


Solution 1:

You’re looking for JSON.stringify().

Solution 2:

Download, 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'){
} else {
  $.getScript('//', winHasJSON)
Related:  How do I require() from the console using webpack?