How to use JSON 2007-05-08

UPDATE : This was written more than 2 years ago, read the new post on How to use JSON.

Web2.0 came with the intensive use of the XMLHttpRequest object even if it was already in our browser before then. A lot of format were tried but JSON will be the winner overall.

What is JSON?

JSON is a format for communication between the server-side (PHP, ASP.NET, …) and the client-side (javascript). The magic of it is that the response from the server-side can be easily converted to an object via the use of the eval() function.

Eval() is a function that gives you the possibility to execute some code in javascript from a string.

eval("alert('This is from eval()')");
This is a bad idea to use it in your code but so easy for JSON that you have to use it.

How to JSON on the server-side?

You can work like an idiot and create your own JSON marshaller for your project or you can go to json.org and use one of the objects that you can find.

I'll take PHP as example. You want to send an object to javascript. You simply do

$response = array();
  $response["id"] = 3;
  $response["message"] = "The object was saved";
  echo(json_encode($response);

It will echo

{id : 3, message : "The object was saved"}

How to JSON on the client-side?

Use the eval() function.

var json = eval(theServerSideJsonTextResponse);
You can now use the json variable created like this
alert(json.id + " : " + json.message);
and it will alert
3 : The object was saved
Beware! There may be an invalid label error here. The solution is to add parenthesis to the response.
var json = eval("(" + eval(theServerSideJsonTextResponse); + ")")
#UPDATE : May 10, 2007 As it was pointed out in the comments, you should never use eval directly when parsing JSON on the client-side. Use a existing JSON parser or a library (jquery is my favorite).

Other formats

For sure there are hundreds of ways of sending back a response to javascript but to my experience, JSON is the best. Let's take a look at the others.

XML is for purists with a lot of time to spend Do you really want to write a XSD (or DTD) for all the calls that can be made to the server? Anyway, it's long to develop because you have to parse it all.

HTML is for lazy people Though it's not completly wrong, laziness is often a bad thing. What do you do if you want to reuse information that you got in a HTML? You parse the HTML to extract the info? please don't…

CSV is for the people that are stuck in the 90s CSV was the coolest thing back in the 90s along with Fresh Prince of Bel-Air.

Watch out for BISON

BISON is nothing else than Binary JSON (see this article). It's lighter than JSON but still unstable. My guess is that we'll all use it sooner or later… but it's just a guess…

comments powered by Disqus