Javascript and JSON

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.

Answers


This is NORMAL

  • In your first case, you are using an object literal.
  • In the second case, this is a string containing data formatted using the JSON data-interchange format.

To de-serialize the string to an object, and assuming you target modern browsers, you could use the native function to do:

var myObj = JSON.parse($.cookie('json_string'));

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:

var myObj = jQuery.parseJSON('{"name":"John"}');

A Note About URL-Encoding

If the string is encoded in the cookie, then you need to decode it first, using decodeURIComponent() like this:

var myObj = JSON.parse(decodeURIComponent($.cookie('json_string')))
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.


Need Your Help

Create a crystal report based on a stored procedure

c# .net stored-procedures dynamic crystal-reports

I want to generate a crystal report dynamically using a stored procedure. I use the the RAS in-process sdk. I already created reports with datasets.