Friday, August 30, 2013

JSON – Introduction


JSON – Introduction

JSON – JavaScript Object Notation

* JSON is lightweight text-data interchange format
* JSON is language independent
* JSON is smaller than XML, and faster and easier to parse.

{ “students” : [ {“name”:”sanjeeva”, “department”:”CSE”},{“name”:”chandima”, “department”:”IT”} ] }

* JSON - Evaluates to JavaScript Objects
The JSON text format is syntactically identical to the code for creating JavaScript objects., therefore without using a parser, can use the a JavaScript built-in eval() function to execute JSON data.

Like XML ,
* JSON is plain text
* JSON is "self-describing" (human readable)
* JSON is hierarchical (values within values)
* JSON can be parsed by JavaScript
* JSON data can be transported using AJAX

Unlike XML ,
* No end tag
* Shorter
* Quicker to read and write
* Can be parsed using built-in JavaScript eval()
* Uses arrays
* No reserved words

JSON Syntax Rules -

JSON syntax is a subset of the JavaScript object notation syntax:
* Data is in name/value pairs
* Data is separated by commas
* Curly braces hold objects
* Square brackets hold arrays

JSON Name/Value Pairs

name (field name) / value pair : "firstName" : "Sanjeeva"
JSON values can be:
* A number (integer or floating point)
* A string (in double quotes)
* A Boolean (true or false)
* An array (in square brackets)
* An object (in curly brackets)
* null 

JSON Objects
* JSON objects are written inside curly brackets,
* Objects can contain multiple name/values pairs:
{ "firstName":"Sanjeeva" , "lastName":"Pathirana", “age”:30 }


JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:
{
"employees": [
        { "firstName":"Sanjeeva" , "lastName":"Pathirana" },
        { "firstName":"Sandamali" , "lastName":"Silva" },
        { "firstName":"Thinuli" , "lastName":"Pathirana" }
    ]
}
In the example above, the object "employees" is an array containing three objects. Each object is a record with a first name and a last name.

JSON Files
* The file type for JSON files is ".json"
* The MIME type for JSON text is "application/json"

Converting a JSON Text to a JavaScript Object

One of the most common use of JSON is to fetch JSON data from a web server (as a file or as an HttpRequest), convert the JSON data to a JavaScript object, and then it uses the data in a web page.

JSON Parser 

The eval() function can compile and execute any JavaScript. This represents a potential security problem.
It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.