Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a multidimensional array in a cookie?

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?

like image 761
StefanE Avatar asked Jan 16 '11 21:01

StefanE


1 Answers

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:

  • An object with no properties (e.g., a "blank" object).
  • An array with four entries.
  • A string.
  • 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 a value.
  • The answer to Life, The Universe, and Everything.

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.

like image 69
T.J. Crowder Avatar answered Oct 20 '22 06:10

T.J. Crowder