Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to JSON

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?

like image 317
dotty Avatar asked Feb 19 '10 10:02

dotty


2 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

like image 114
JonoW Avatar answered Oct 14 '22 06:10

JonoW


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)) 
like image 37
Stancho Stanchev Avatar answered Oct 14 '22 05:10

Stancho Stanchev