Reputation: 7630
Today I have a Ajax solution where the server keeps track of selections are doing and updates the page. I'm redoing this so it will be all done with javascript on the client until the user actually submit the data, performance where quite bad under load with the old solution. (C#, ASP.NET 4.0)
Found a nice way of storing an Array by first serialize it with json link text
Say I have an array like this: {Id, Value}
Any advise how I can store several of the arrays above to a cookie?
Upvotes: 7
Views: 6768
Reputation: 1494
Converting an array into a string:
> JSON.stringify([1, 2])
*returns* '[1, 2]'
We can then make it a cookie:
> $.cookie('cookie', '[1, 2]')
And then parse it:
> JSON.parse($.cookie('cookie'))
*returns* [1, 2]
Upvotes: 1
Reputation: 1074268
Say I have an array like this: {Id, Value}
That's not an array. That's an object. You can multiple copies of those in an array:
[
{"foo": "bar"},
{"foo": "baz"},
{"foo": "boom"}
]
That's a valid JSON string for an array containing objects —in this case, objects with a single property, foo
, each of which has its own value, but the objects don't have to have the same properties, and they can have multiple properties. For instance:
[
{},
["zero", "one", "two", "three"],
"I'm just a string",
{
"f0": "foo zero",
"f1": "foo one",
"f2": "foo two",
"all": ["foo zero", "foo one", "foo two"]
},
42
]
That's a valid JSON string for an array with five entries:
f0
, f1
, f2
, and all
. f0
, f1
, and f2
all have string values; all
has an array of strings as a value.You can turn an object or array into a valid JSON string (stringify), and reverse the process (parse) client-side using any of several libraries. Crockford (the inventer of JSON) has several on his github page, most notably json2.js although json2.js relies on eval
for parsing; since that's not really ideal you can use json_parse.js
(a recursive descent parser that doesn't use eval
) or json_parse_state.js
(a state machine that doesn't use eval
) instead.
Upvotes: 6
Reputation: 1306
Cookies only store simple strings. You can come up with you own system something like this:
$content = [id,value];[text,textvalue];
setcookie("Array", $content);
When you want it back, you explode the string at delimiters (in this case ';' and ',')
Upvotes: 1
Reputation: 116110
Use JSON.stringify
to generate a string from the array object.
http://msdn.microsoft.com/en-us/library/cc836459(v=vs.85).aspx
Upvotes: 1