212

How can I serialize an object to JSON in JavaScript?

Michał Perłakowski
  • 80,501
  • 25
  • 149
  • 167
maxaposteriori
  • 7,099
  • 4
  • 27
  • 24

3 Answers3

296

You're looking for JSON.stringify().

Michał Perłakowski
  • 80,501
  • 25
  • 149
  • 167
Mike_G
  • 15,551
  • 12
  • 67
  • 98
  • 1
    Using JSON.stringify() with javascript objects containing arrays have a little thing to it. Please check my question: http://stackoverflow.com/questions/25423883/parsing-json-array-gives-error – uylmz Aug 21 '14 at 12:33
53

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

var json_data = JSON.stringify(obj);
bartektartanus
  • 14,101
  • 5
  • 73
  • 98
Johannes Weiss
  • 50,352
  • 15
  • 99
  • 134
  • 1
    Should I really need to include "json2.js"? It seems to works without it. – Pavel Alexeev Mar 31 '12 at 08:28
  • 32
    @PavelAlexeev No, you don't neet to include `json2.js` anymore, unless you are targetting very old browsers: modern browsers include a native implementation of the `JSON` object. The good thing about `json2.js` is that it will only kick in if no native object is found. See [http://stackoverflow.com/questions/891299/browser-native-json-support-window-json] for a detailed breakdown of browser support. – Edurne Pascual May 10 '12 at 08:14
5

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)
}
AvL
  • 3,033
  • 1
  • 27
  • 39