Recently JSON has become a very popular data interchange format with more and more developers and a large number of big players in the web arena opting for it over XML.  In this article we will explore what json is all about and how we can use it. We will proceed in the following manner:

  • Definition, Characteristics and Structure of json

  • Example

  • Parsing json text

  • Reading values from json

Let’s go through each of these one by one.

Definition, Characteristics and Structure of json

JSON which stands for JavaScript Object Notation can be defined as a lightweight data interchange format. It is also said a fat-free lightweight alternative to xml. It is a text format which is programming language independent and is native data form of JavaScript. It is lighter and faster than xml. The credit to make json popular goes to Douglas Crockford.

Since JSON is the native data form of JavaScript, it can be used on the client side in an Ajax application more easily then XML. Implementations of JSON has been done in most of the languages (check here) we will stick to javascript as of now.

A JSON object starts with { and ends with }.  In between you can have key value pairs which are enclosed with double quotes (“) and separated by a colon (:).

Keys are simple strings and values can be either array, string, number or Boolean. Values enclosed between { and } are objects and those between [ and ] are arrays.

Example

A JSON can be as simple as

{name:”name1”, “age”:25, ”address”: "anywhere"
}

Example 1
An example using arrays

{
"name": "name1", "age":"25", "phoneNumbers": ["9999123456", "9999678900","1234567890" ]
}

Example 2
A more complex example which has values in objects and objects are array elements.

{
"results":
 {
   "students":
   [
     {
      "id" : "1",
      "name": "Ramu"
     },
     {
      "id": "2",
      "name": "Shyamu"
     },
     {
      "id" : "3",
      "name": "Damu"
     }
   ]
 }
}

Example 3

Those familiar with JavaScript will see that syntax is same we use while declaring objects in JavaScript.In the above example we have a json where results is the key and its value is an object.

Read the rest of this entry »

Technorati Tags: ,