Javascript and JSON

This will work :

var json = { 'items': [{ 'id': 72, 'quantity': 1, 'format': '90ml' }, { 'id': 72, 'quantity': 4, 'format': '70ml'}] }

This will NOT work :

var json = $.cookie('json_string');

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

  • 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

error while implementing layout in android

android android-layout

I am new to android .While implementing a Tab view in Android application I am getting an sort of error where I am not able to see the view/layout.

Mailbox unavailable. The server response was <> No such user here email iis-7 sendmail

Recently we've upgraded a clients website from our IIS6 server to our new IIS7 server and they are receiving the following error on occassion when sending out emails:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.