views:

139

answers:

3

Hay I have an Array (var cars = []) which hold 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. But i want to send it as a JSON object.

How do i convert an array to a JSON object?

+5  A: 

Take this script: http://www.json.org/json2.js

And call:

var myJsonString = JSON.stringify(yourArray);
JonoW
This works, does jQuery have a function like this? I'd prefer not to attach another js file if jQuery has a function already.
dotty
jQuery has the implementation of JSON.parse in 1.4.1, but not JSON.stringify... If you minifiy json2.js its <3k I think.
gnarf
Yeah I was suprised jQuery didn't have this built in too
JonoW
Got json2.js down to 3,334 bytes. This will have to do for the time being. Thanks JonoW and gnarf
dotty
A: 

From version 1.4.1 of JQuery you could also use JQuery.parseJSON directly.

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
Obalix
This appears to be parsing a JSON object, i want to convert an Array to a JSON object.
dotty
+2  A: 

There's a jQuery plugin for that here:

http://code.google.com/p/jquery-json/

Eric