Friday, September 16, 2011

JSON - Javascript Object Notation


When you build an AJAX-enabled website, you must know how to communicate with the server from the client and vice versa. The most-used data interchange format is JSON (Javascript Object Notation). JSON is a lightweight data-interchange format that based on Javascript. Many developer use JSON when sending data to the server along with the request. JSON can hold simple data and complex data (array, object, etc). JSON is more popular than XML because of its speed. JSON absolutely faster than XML.

There are 2 ways to create JSON and send it to the server :
1. Directly create string JSON.
2. Create javascript object and then convert the object into string JSON.

To directly pass JSON to the server without parsing it, you must create string JSON directly.

The syntax is :

var myJSON = "{ some data }";


Here is the example of simple JSON format :









In the example above, we can say that person is an object with 3 properties (PersonID, Name, Gender). The object then stored in string JSON format. JSON can hold complex object like array or array of object like below :





The code above create string JSON that hold array of object. The name of array is Person and it holds two object as its elements (Steve and Lily).

When you use JSON string, you can send it directly to the server without any parsing method. But, you can't easily access its content with dot notation in javascript before you send it to the server. To easily access the content, you must create the javascript object first, and then parse it to the string JSON before send it to the server.. Here is the example :

syntax :

var myJSON = { some data };

Remember that unlike the string JSON, there is no quotes before and after the curly braces. Here is the example :




You can access the element of  JSON with dot notation, like person.Name , person. Age ,etc...
For the complex object, the syntax is same with the string JSON except that there is no quotes before and after the curly braces..

When you use normal JSON, you must convert it to string JSON before you send it to the server via Jquery AJAX.. There is a jquery plug-in for parsing JSON, you can download it in the link below :


After add the script in your page, you can easily parse the JSON to the string JSON with the syntax lik this :

$.toJSON(myJSON);

int the code above, myJSON is a JSON variable..

With JSON, you can easily send and receive your complex data from client to the server and vice versa. JSON is fast and light data interchange format.

To send the JSON to the server with Jquery AJAX, i will explain that in my next post... Hopefully this post will help solve your problem.. For any question, please send email to stevechristopher91@gmail.com or in my Facebook . Thanks..!

No comments:

Post a Comment