This will work :
var json = { 'items': [{ 'id': 72, 'quantity': 1, 'format': '90ml' }, { 'id': 72, 'quantity': 4, 'format': '70ml'}] }
alert(json.items[1].id);
This will NOT work :
var json = $.cookie('json_string');
alert(json.items[1].id);
the json_string in the cookie is EXACTLY the same as in example #1. After fooling around, I realized I need to do this to make it work:
eval("var json = " + $.cookie("json_cart"));
Is this the correct way to do it? It seems like a hack, im facing some challenges when trying to make this javascript / c# json communication, i tought it would be very easy. Anyway. At least I got it running now.
This is NORMAL
To de-serialize the string to an object, and assuming you target modern browsers, you could use the native function to do:
Or you could import json2.js from the official JSON website and use the same line as above.
Or, as mentioned by subhaze, you can be completely jQuery-y and use:
A Note About URL-Encoding
If the string is encoded in the cookie, then you need to decode it first, using
decodeURIComponent()like this:A Note About Quoted Keys
Your JSON is actually invalid, as it requires double-quoted keys. You should use double-quotes (
") to wrap around your keys and your string values.Check It
To quickly check for the validity of your JSON, try JSONLint.
Your question is very similar to others. So, in the future, be sure to check for similar questions first by checking the JSON tag or searching for your issue.