Tuesday, February 28, 2012

JSON: JavaScript Object Notation

JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.

JSON stands for JavaScript Object Notation
JSON is lightweight text-data interchange format
JSON is language independent *
JSON is "self-describing" and easy to understand

*JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

Much 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

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

Deference between json and xml:
For AJAX applications, JSON is faster and easier than XML:

Using XML
Fetch an XML document
Use the XML DOM to loop through the document
Extract values and store in variables

Using JSON
Fetch a JSON string
eval() the JSON string 

JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax.
1.       Data is in name/value pairs
2.       Data is separated by comma
3.       Curly brackets holds objects
4.       Square brackets holds arrays

JSON Name/Value Pairs
·         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
Eg:  "firstName" : "John"

JSON Objects
JSON objects are written inside curly brackets,
Objects can contain multiple name/values pairs:
Eg:  { "firstName":"John" , "lastName":"Doe" }

JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:
 "employees": [
 { "firstName":"John" , "lastName":"Doe" },
 { "firstName":"Anna" , "lastName":"Smith" },
 { "firstName":"Peter" , "lastName":"Jones" }

JSON Uses JavaScript Syntax

Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:
var employees = [
 { "firstName":"John" , "lastName":"Doe" },
 { "firstName":"Anna" , "lastName":"Smith" },
 { "firstName":"Peter" , "lastName": "Jones" }

Converting a JSON Text to a JavaScript Object

var obj = eval ("(" + employees + ")");

 First Name: <span id="fname"></span><br />
 Last Name: <span id="lname"></span><br />

 <script type="text/javascript">
 document.getElementById("fname").innerHTML = obj.employees[1].firstName
 document.getElementById("lname").innerHTML = obj.employees[1].lastName

No comments:

Post a Comment