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?
 
    
    - 85,173
- 29
- 368
- 345
 
    
    - 40,405
- 66
- 150
- 195
- 
                    Just double-checking: is the array you want to send to the page a JavaScript array or is it on the server? – Ian Oxley Feb 19 '10 at 10:22
- 
                    it's a Javascript array, I will be sending it to a Python script and Python will use the JSON string and work with that. – dotty Feb 19 '10 at 10:24
- 
                    https://stackoverflow.com/questions/2295496/convert-array-to-json/71512964#71512964 – mehmet Mar 17 '22 at 13:36
12 Answers
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
 
    
    - 9,886
- 7
- 43
- 64
 
    
    - 14,029
- 3
- 33
- 31
- 
                    5This works, does jQuery have a function like this? I'd prefer not to attach another js file if jQuery has a function already. – dotty Feb 19 '10 at 10:27
- 
                    1jQuery has the implementation of JSON.parse in 1.4.1, but not JSON.stringify... If you minifiy json2.js its <3k I think. – gnarf Feb 19 '10 at 10:36
- 
                    6
- 
                    Got json2.js down to 3,334 bytes. This will have to do for the time being. Thanks JonoW and gnarf – dotty Feb 19 '10 at 10:44
- 
                    132for anyone still reading this answer, it's worth pointing out that all modern browsers include the `JSON` object as standard, which means that **you don't need this script** unless you're planning to support older browsers like IE7 or Firefox 3.0. See [CanIUse](http://caniuse.com/json) for the support chart. – Spudley May 26 '13 at 21:35
- 
                    @Spudley, this answer helped me as Mongo Console uses JS but it didn't like printing an array. – AnneTheAgile Jun 01 '14 at 23:02
- 
                    1It's worth pointing out you can do this in a browser console: var a = [paste]; JSON.stringify(a) – Michael Cole Jan 15 '15 at 03:27
- 
                    https://stackoverflow.com/questions/2295496/convert-array-to-json/71512964#71512964 – mehmet Mar 17 '22 at 13:36
- 
                    @Spudley it would be nice to add a context, e.g. SQLite does not support JSONs directly and you still have to store them as strings. `FormData` also does not support JSON but only a form element. `XMLHttpRequest.send` also does not support JSON directly. So the only thing that really commonly supports JSON is JS code itself and `jQuery.ajax` in `data`. – jave.web May 20 '22 at 05:35
- 
                    
I made it that way:
if I have:
var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;
var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);
to convert pluginArrayArg (which is pure javascript array) into JSON array:
var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
 
    
    - 889
- 7
- 3
- 
                    
- 
                    https://stackoverflow.com/questions/2295496/convert-array-to-json/71512964#71512964 – mehmet Dec 22 '22 at 06:45
Wow, seems it got a lot easier nowadays... 3 ways you can do it:
json = { ...array };
json = Object.assign({}, array);
json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
 
    
    - 931
- 8
- 9
- 
                    6
- 
                    https://stackoverflow.com/questions/2295496/convert-array-to-json/71512964#71512964 – mehmet Mar 17 '22 at 13:36
Answered in 2022 ;)
If you want json String
var JsonString = JSON.stringify(JsArray);
If you want json Object
var JsonObject = JSON.parse(JSON.stringify(JsArray));
More details!
Using
JSON.stringify(), we convert the JavaScript array to Json string. And usingJSON.parse(), we convert Json string to a Json object.
 
    
    - 506
- 3
- 12
One other way could be this:
        var json_arr = {};
        json_arr["name1"] = "value1";
        json_arr["name2"] = "value2";
        json_arr["name3"] = "value3";
        var json_string = JSON.stringify(json_arr);
 
    
    - 737
- 7
- 10
I decided to use the json2 library and I got an error about “cyclic data structures”.
I got it solved by telling json2 how to convert my complex object. Not only it works now but also I have included only the fields I need. Here is how I did it:
OBJ.prototype.toJSON = function (key) {
       var returnObj = new Object();
       returnObj.devid = this.devid;
       returnObj.name = this.name;
       returnObj.speed = this.speed;
       returnObj.status = this.status;
       return returnObj;
   }
 
    
    - 3,555
- 2
- 29
- 34
Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.
 
    
    - 1,214
- 13
- 24
because my array was like below: and I used .push function to create it dynamically
my_array = ["234", "23423"];
The only way I converted my array into json is
json = Object.assign({}, my_array);
 
    
    - 3,581
- 1
- 41
- 45
Shortest
To generate valid json from array of integers use
let json = `[${cars}]`
for more general arrays use JSON.stringify(cars) (for object with circular references use this)
let cars = [1,2,3]; cars.push(4,5,6);
let json = `[${cars}]`;
console.log(json);
console.log(JSON.parse(json)); // json validation 
    
    - 85,173
- 29
- 368
- 345
If you have only 1 object like the one you asked, the following will work.
var x = [{'a':'b'}];
var b= JSON.stringify(x);
var c = b.substring(1,b.length-1);
JSON.parse(c); 
 
    
    - 3,368
- 5
- 32
- 47
 
    
    - 52
- 1
- 4
You can convert an array to JSON using the Object.assign function. The main issue that I hit with that is that Javascript arrays have a zero based integer key, which in turn allows to access the data in the array.
let fruits = ['Apple', 'Banana']
document.write(fruits[0])
Returns:
Apple
When you convert the array to JSON, you get
{"0": "Apple", "1: "Banana"}
JSON objects on the contrary usually contain arbitrary keys, such as:
{ "some_key": "some value", "other_key: "some other value" }
Happily, you can create a list of items, which works pretty much as an array and then use Object.assign as if it was an array, then convert the output to a JSON object
var items = {};
items["some_key"]="some value";
items["other_key"]="some other value";
const jsonString = JSON.stringify(Object.assign({}, items)) 
const json_obj = JSON.parse(jsonString);
The advantage of working with item lists is that you don't have to deal with the JSON data as a string or quotes, commas etc... You can instead just manage the item object filling data in or removing it. When you are done you just convert the item variable to a JSON object and do whatever you need to do with it.
 
    
    - 308
- 2
- 12
With your cars array: var cars = [2,3,..]. You can use for loop like this
    var carArray = new Array();  
    for(var c in cars) {
      var jsonObj = new Object();
      jsonObj.car_id = cars[c];
      carArray.push(jsonObj);
    }
    
 
    
    - 147
- 7