Storing a multidimensional array in a cookie?

Today I have an Ajax solution in which the server tracks the selection and refreshes the page. I am redoing this so that everything will be done with javascript on the client until the user sends the data, the performance is where it is pretty bad under load with the old solution. (C #, ASP.NET 4.0)

Found a good way to store an array by first serializing it using json link text

Say I have an array like this: {Id, Value}

How can I save multiple arrays above in a cookie?

+7
source share
4 answers

Say I have an array like this: {Id, Value}

This is not an array. This is an object. You can use multiple copies in an array:

[ {"foo": "bar"}, {"foo": "baz"}, {"foo": "boom"} ] 

This is a valid JSON string for an array containing objects - in this case, objects with one property, foo , each of which has its own value, but the objects should not have the same properties, and they can have several properties. For example:

 [ {}, ["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 ] 

This is a valid JSON string for an array with five entries:

  • An object without properties (for example, an "empty" object).
  • An array with four elements.
  • Line.
  • An object with four properties: f0 , f1 , f2 and all . f0 , f1 and f2 all have string values; all has an array of strings as value.
  • The answer to Life, the Universe and Everything.

You can turn an object or an array into a valid JSON string (stringify) and cancel the process (parsing) on ​​the client side using any of several libraries. Crockford (a JSON investor) has several githubs on his page , primarily json2.js, although json2.js relies on eval for parsing; since this is not entirely ideal, you can use json_parse.js (a recursive descent parser that does not use eval ) or json_parse_state.js (a state machine that does not use eval ).

+7
source

Converting an array to a string:

 > JSON.stringify([1, 2]) *returns* '[1, 2]' 

Then we can make this cookie:

 > $.cookie('cookie', '[1, 2]') 

And then analyze it:

 > JSON.parse($.cookie('cookie')) *returns* [1, 2] 
+2
source

Use JSON.stringify to create a string from an array object.

http://msdn.microsoft.com/en-us/library/cc836459(v=vs.85).aspx

+1
source

Cookies store only simple lines. You can come up with your own system like this:

 $content = [id,value];[text,textvalue]; setcookie("Array", $content); 

When you want to return, you will blow up the line in the delimiters (in this case ";" and ",")

+1
source

All Articles