Header

Wednesday, October 8, 2014

Introduction to JSON


JSON stands for JavaScript Object Notation, is a simple and easy to read, write, store and exchange data format. It has become popular worldwide as it is being used in  infinite projects. JSON is a best alternative solution for XML.

What is JSON
  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is platform/language independent
  • JSON is “self-describing” and “self understandable”

Extension
   JSON filename extension is .json

MIME type
   JSON Internet Media type is application/json

Programming language support
  JSON is language independent and it is supported by most of all the programming languages:

Uses of JSON
  • JSON is used when writing JavaScript based application which includes browser and websites.
  • JSON format is used for serializing & transmitting structured data over network connection.
  • JSON is primarily used to transmit data between server and web application.
  • Web Services and API.s use JSON format to provide public data. Eg. Twitter
  • JSON can be used with modern programming languages like Java, C# etc.,

JSON Syntax

Let’s discuss about JSON basic sytax. JSON syntax is primarily considered as a subset of JavaScript syntax.

JSON Syntax Rules

JSON syntax is as follows:
  • Data is in name/value pairs.
  • Data is separated by commas.
  • Curly braces hold objects
  • Square brackets hold arrays

Let’s discuss about JSON basic sytax. JSON syntax is primarily considered as a subset of JavaScript syntax.

JSON Syntax Rules

JSON syntax is as follows:
  • Data is in name/value pairs.
  • Data is separated by commas.
  • Curly braces hold objects
  • Square brackets hold arrays
JSON Data (Name/Value pairs)

JSON data is specified as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
“Language” : “JSON”
This is human readable and simply understood as:
Language = “JSON”

JSON Objects (Name/Value pairs)

JSON objects are mentioned inside curly brackets,
Objects can contain multiple name/values pairs or even array:
“Language”:”JSON” , “Author”:”Douglas Crockford”

JSON Arrays

JSON arrays are written inside square brackets.

An array can contain multiple objects:
{
“Languages”: [
{ "Language":"C" , "Creator":"Dennis Ritchie" },
{ "Language":"C++" , "Creator":"Bjarne Stroustrup" },
{ "Language":"Java" , "Creator":"James Gosling" }
]
}


Quick recap
  • Data is represented in name/value pairs
  • Curly braces hold objects and each name is followed by ‘:’(colon). The name/value pairs are separated by , (comma).
  • Square brackets hold arrays and values are separated by ,(comma).

JSON Datatypes
JSON supports following datatypes:

Number
String
Boolean
Array
Object
null

Number
It can be a decimal integer or decimal floating point number. Octal and hexadecimal formats are not supported.
Syntax
var json_num_obj = { “string” : number_value1, string : number_value2…….}
Usage
var json_student= { “maths”: 80, “science” : 87, “social” :78}

String
It is a sequence of zero or more characters put inside as double quotes.
Syntax
var json_str_obj = { “string” : “str_value1″, “string” : “str_value2″…….}
Usage
var json_str_fullname = { “firstName”:”Programmer” , “lastName”:”Guru” }

Boolean
It includes true or false values.
Syntax
var json_bool_obj = { “string”: true/false…….}
Usage
var json_stud_rank = { “distinction”:true , “class topper”:true }

Array

  • It is an ordered collection of values.
  • The values are enclosed square brackets which means that array begins with ‘[' and ends with ']‘
  • The values are separated by ,(comma).
  • Array index starts from 0.

Syntax
var json_bool_obj = { “string1″: [
{"string2": "string":"value"},
{"string2": "string":"value"},
{"string2": "string":"value"},
]
}
Usage
var json_lang_array =
{ “languages”: [
{ "language":"C" , "Creator":"Dennis Ritchie" },
{ "language":"C++" , "Creator":"Bjarne Stroustrup" },
{ "language":"Java" , "Creator":"James Gosling" }
]
}

Object

  • It is an unordered set of name/value pairs.
  • Object are enclosed in curly braces like it starts with ‘{‘ and ends with ‘}’.
  • Each name is followed by ‘:’(colon) and the name/value pairs are separated by , (comma). Make sure both name and value are enclosed within double quotes.
  • The keys must be strings and should be different from each other.

Syntax
var json_bool_obj = { “string1″: “value”.”string2″:”value”……..}
Usage
var json_obj = { “Language”:”JSON” , “Author”:”Douglas Crockford”}

Null
It means empty type.
Syntax
var json_null_obj = { “Language”:null }
Usage
var i = null;
if(i==1)
{
document.write(“<h1>value is 1</h1>”);
}
else
{
document.write(“<h1>value is null</h1>”);
}


JSON vs XML

Similarities between JSON and XML:

  • JSON is plain text like XML
  • JSON is “self-describing”(human readable) and “self-understandable” as XML
  • JSON is hierarchical (values within values)
  • JSON can be parsed by JavaScript
  • JSON data can be transported using AJAX


Differences between JSON and XML:

  • No end tag like XML
  • Shorter than XML
  • Quicker to read and write when compare to XML
  • Can be parsed using built-in JavaScript functions like eval() and parse()
  • Uses arrays – Efficient for handling huge data
  • No reserved words


Why JSON?
JSON is faster and easier than XML when you are using it in AJAX web applications:
Steps involved in exchanging data from web server to browser involves:

Using XML

  • Fetch an XML document from web server
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
  • It also involves type conversions

Using JSON
Fetch a JSON string
Parse the JSON string using eval() or parse() javascript functions

JSON Parsing
JSON string can be parsed using following JavaScript functions:
eval()
parse()

Using eval()
The eval() function can be used to convert the well formed JavaScript Object Notation(JSON) string into an object.
Invoke eval() to convert JSON string to object
var contact= eval(“(“+’{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:["999-9999-909","999-9999-999"]}’+”)”);

Don’t forget to embed JSON string with function brackets “(” and “)”.

Get values using JSON object
alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);

Using parse()
The eval() function can also be used to convert the well formed JavaScript Object Notation(JSON) string into an object.
Invoke parse() to convert JSON string to object
var contact= JSON.parse(‘{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:["999-9999-909","999-9999-999"]}’);

Get values using JSON object
alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);


eval() Vs parse()

  • JSON.parse() function is not supported by all browsers since the native support for the function is missing in old browsers. Check what are all browsers support JSON.parse() from here.
  • JSON is just a subset of JavaScript. JSON.parse() just parses JSON string present in JavaScript but eval evaluates the full JavaScript language and not just the subset that’s JSON which end up in parsing function calls and other JavaScript code.
  • Time taken for parsing matters: JSON.parse() parses JSON string in quick time when compare to eval().

No comments:

Post a Comment