Convert array to JSON

dotty picture dotty · Feb 19, 2010 · Viewed 1.2M times · Source

I have an Array var cars = [2,3,..] which holds a few integers. I've added a few values to the array, but I now need to send this array to a page via jQuery's .get method. How can I convert it to a JSON object for sending?

Answer

JonoW picture JonoW · Feb 19, 2010

Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

And call:

var myJsonString = JSON.stringify(yourArray);

Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below