Monday, August 10, 2009

Extracting a JSON array from a cookie

Knowing nothing, I had assumed that when you JSON-ify an array, then parse it back into an object, it comes out exactly as it went in. No so, gentle reader. Arrays are stored as named objects:

 "spells":{"0":{"0":113,"1":135},"1":{},"2":{"0":227},"3":{"0":209,"1":186}}  


This means all arrays must be reconstituted manually:

 // spells     
if (chardata.spells != null) {
char_spells = [];
for (spell_lvl_idx in chardata.spells) {
char_spells.push([]);
for (char_spell in chardata.spells[spell_lvl_idx]) {
char_spells[parseInt(spell_lvl_idx)].push(parseInt(chardata.spells[spell_lvl_idx][char_spell]));
}
}
chardata.spells = char_spells;
}


In this case, a multi-dimensional array of [spell level[spells per level]].

2 comments:

Michael R. Head said...

What are you using to serialize/sanitize your objects to JSON? JSON definitely allows for the storage of arrays...

Felonious Ham said...

I thought Blogger was supposed to notify me when I had a comment!

In any case, yeah. There's probably a better way, but when I save it off, it comes back as a "number keyed" object (which is just what an array is anyway).