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["id"] = 3;
-
$response["message"] = "The object was saved";
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…


RSS without the echo chamber
This example seems wrong to me.
I’m not familiar with php, so not sure how the “array()” constructor works. But a proper server-side array should be serialized to json like this, “[’item1′, ‘item2′, ‘item3′]”.
The curly brackets “{}” are used for objects, not arrays. Hence this example is converting a server-side array into an object on the client, which does not seem very logical. (Pardon me if my I’m wrong, and the array() in php actually creates a object.)
A better example would be (found at http://no.php.net/array):
$array = array();
$array[0] = ‘zero’;
$array[1] = ‘one’;
$array[2] = ‘two’;
$array[3] = ‘three’;
Which would be serialized into:
“[’zero’, ‘one’, ‘two’, ‘three’]”.
Also, I would recommend using the parseJSON method found in json.js (http://www.json.org/js.html), instead of eval, since eval is a bit scary when evaling json from an untrusted source.
My two cents…
Einar
Well, I think it should be also mentioned that currently there are many libraries which supports JSON both on server side and on client side.
For example, the JSONER library provides very convenient utilities for working with data in JSON form on client side (i.e. withing browser) and allows to simply most of JSON related operations significantly.
URL for library, documentation and examples is
http://www.soft-amis.com/jsoner/index.html
I think it should also be noted that this method of working with JSON has a security risk, as talked about in http://www.fortifysoftware.com/servlet/downloads/public/JavaScript_Hijacking.pdf.
If you would like a solution and just skip the PDF, it is to make your JSON response with something like “/*-secure-\n{id : 3, message : “The object was saved”}\n*/”. When you get that string back, remove the “/*-secure-\n” and “\n*/” from the beginning and end and then perform your eval.
Argh! Eval = EVIL! Do NOT use it! Find yourself a JSON parser!
http://www.json.org/js.html
Thanks to all for your comments… I updated the post.
@Einar : I wanted to cut it short on the example. If you use an array as a hash-object in PHP, it will return it has an object.
I could also have written :
[…] How to use JSON | Javascript Kata (tags: json tutorial javascript) […]
“JSON is a format for communication between the server-side (PHP, ASP.NET, …) and the client-side (javascript).” - by Dan
Sorry, I can’t agree with it… it’s a shame to think in JSON just as a format for communication between the server-client sides… nowadays it’s an extremely piece of javascript. Please check http://en.wikipedia.org/wiki/JSON for a better brief of JSON.
“Argh! Eval = EVIL! Do NOT use it!” - by zack
Nooooo it’s so lame to tell Eval = Evil oO;; it’s the same as saying SQL = Evil just because if bad implemented it makes possible SQL-Injections… eval() has it good applies too.
@Fabio
I began to use JSON for communication between different services… not just server-side and client-side. It is light-weight and easy so you’re right when you say that it’s not just that…
I’m new to JSON. I have been using CSV-type formats to return all kinds of values to my running javascript. Other than CSV being from the ’90s, why should I use JSON instead?
@Charlie
JSON is just fast to develop. The json object created from the response is ready-to-use. You don’t have to parse the response like you’ll do with CSV. Also, it’s just that easy on the server-side to create a json response…
Once you have those JavaScript objects, you’ll likely want to “inject” some of the contained data into a document. IBDOM: http://ibdom.sourceforge.net/ eases this process with a “populate()” method added to a DOM HTMLElement: $e(”someElement”).populate(someObject); I’m seeking some beta testers. We’ve been using internally, and i’m in the process of refactoring several applications to use this.
[…] How to use JSON | Javascript Kata (tags: javascript json) […]
To: Charlie May
There is nothing wrong with CSV. It’s just that JSON is capable of storing much more complex data than you would attempt using CSV. A CVS example might be a file of orders and a file of the line items on those orders. Using JSON you could store each order and it’s related line items is a JSON structure called Order. Then take the group of Orders for the day and call it Daily Business, at which time you can include end of day, customer changes, whatever.
JSON makes it easier to transfer both data and structure between systems. Access to these more complex data structures allows new solutions to be envisioned.