views:

84

answers:

3

This is royally annoying me at the moment:

Consider an array of 2 values:

var myArray = new Array();
myArray.push(21031);
myArray.push(21486);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:

["21031","21486"]

Now consider an array of a single value:

var myArray = new Array();
myArray.push(21239);

When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:

21239

This is almost completely useless to me as when I pull the items from the cookie, one comes back as a single value, the other comes back as an array that I can iterate over....ahhh!

Why?

A: 

Cookies are strings, so all you are doing is storing a string serialisation of the array. If I do:

document.cookie = [1, 2].toString()

then document.cookie has the value "1,2", which is not an array.

EDIT: as toJSON isn't a native jQuery method, it presumably comes from a plugin. Have you checked the plugin documentation? Alternatively, try a different plugin that works as you expect.

NickFitz
+1  A: 

You're doing something wrong. Regardless of what JSON lib you're using (presuming it actually works), serializing this:

[21031, 21486]

should produce this:

"[21031,21486]"

Not ["21031","21486"] as you've posted. That looks like you're serializing the individual elements. Post more code.

Crescent Fresh
+3  A: 

I'd suggest using json2.js' JSON.stringify. It gets both of those cases right:

// [] is the same as new Array();
var foo = [];

foo.push(1);
foo.push(2);

JSON.stringify(foo); // "[1, 2]"

var bar = [];

bar.push(1);

JSON.stringify(bar); // "[1]"

In addition, when you use the json2.js API, your code automatically takes advantage of browser-native functionality in newer browsers.

Dave Ward