A short tutorial about JSON

JSON stands for JavaScript Object Notation and it is a subset of JavaScript that is fully interpreted by the language as new objects and variables. It has two main uses.

Streamline AJAX applications

Normally an AJAX application will work by issuing small GET and POST requests and getting XML string back in return. Not only are these XML string quite large in themselves, but the need to be parsed before they can be used. This causes a double overhead as JavaScript XML parsing can be quite cumbersome.

With JSON you can just send the string across. You only need to call the eval() function in order to get it working. After this call all of the objects and variables defined therein are ready for use straight away.

Script Packaging

JSON allows you to write JavaScript libraries that are easy to understand. Take a look at some libraries like Prototype, script.aculo.us or SIMILE Timeline and you will see that they are all packaged in JSON format.

Writing your own packages in JSON will allow you to easily understand it in 6 months time as it will be self evident what things are doing from the structure created. Additionally, if you write your own JSON packages the functions that they use won’t conflict with each other.

JSON Is Easy!

The best thing about JSON is how easy it is to write in this style. Lets write a simple object in JSON called obj with the variables var1 and var2, and a function called print.


var obj = {
    var1 : 1,
    var2 : 2,
    print : function(){
        alert(obj.var1+’ ‘+obj.var2);
    }
}

That’s it! Just separate variable or function names from their values by a colon. If you are running this locally you can just copy this object into a new variable in order to get a working copy of it, like so:


var myObj = obj;

Then, in order to call any functions or use any variables you just use the standard dot notation.


myObj.var1 = 3;
myObj.print();

When using JSON in conjunction with AJAX you need to run the JSON variable through the eval() function to get it all working. In the following example the argument json is the value retreived from the server.

var myObj = eval(”(” + json + “)”);

You need to make sure you put in the face braces in order to pass eval() a correctly parsed string. As an alternative you could use the following, which has the same effect.

eval(”var myObj=”+json);

There is one thing that you have to be aware of with JSON.

this In Not What It Seems

The this keyword doesn’t do exactly what you would expect from the usual object orientated language. This is because, in JavaScript, everything is an object, even the functions. So the this keyword would reference the function that it is currently run in. To get around this issue you can just use the object name rather than the this variable.

Adding JSON to part of your JavaScript skill set can only be a good thing.

Phil
Programmer, Research and Development

  • Digg
  • del.icio.us
  • StumbleUpon

Leave a Reply