Wednesday, March 15, 2017

JSON – Objects



-                    Creating Simple Objects:

JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript −
  • Creation of an empty Object −
var JSONObj = {};
  • Creation of a new Object −
var JSONObj = new Object();

·        Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator –
·         var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };

·         This is an example that shows creation of an object in javascript using JSON, save the below code as json_object.htm –

·         <html>
·            <head>
·               <title>Creating Object JSON with JavaScript</title>
·          
·               <script language = "javascript" >
·          
·                  var JSONObj = { "name" : "tutorialspoint.com", "year"  : 2005 };
·                   
·                  document.write("<h1>JSON with JavaScript example</h1>");
·                  document.write("<br>");
·                  document.write("<h3>Website Name = "+JSONObj.name+"</h3>"); 
·                  document.write("<h3>Year = "+JSONObj.year+"</h3>"); 
·          
·               </script>
·                   
·            </head>
·          
·            <body>
·            </body>
·          
·         </html>
Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the following result –


-                    Creating Array Objects:

The following example shows creation of an array object in javascript using JSON, save the below code as json_array_object.htm 
<html>
   <head>
      <title>Creation of array object in javascript using JSON</title>
                 
      <script language = "javascript" >
 
         document.writeln("<h2>JSON array object</h2>");
 
         var books = { "Pascal" : [ 
            { "Name"  : "Pascal Made Simple", "price" : 700 },
            { "Name"  : "Guide to Pascal", "price" : 400 }],  
                                   
            "Scala"  : [
               { "Name"  : "Scala for the Impatient", "price" : 1000 }, 
               { "Name"  : "Scala in Depth", "price" : 1300 }]    
         }    
 
         var i = 0
         document.writeln("<table border = '2'><tr>");
                          
         for(i = 0;i<books.Pascal.length;i++){      
            document.writeln("<td>");
            document.writeln("<table border = '1' width = 100 >");
            document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>");
            document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>");
            document.writeln("</table>");
            document.writeln("</td>");
         }
 
         for(i = 0;i<books.Scala.length;i++){
            document.writeln("<td>");
            document.writeln("<table border = '1' width = 100 >");
            document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>");
            document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>");
            document.writeln("</table>");
            document.writeln("</td>");
         }
                          
         document.writeln("</tr></table>");
 
      </script>
 
   </head>
         
   <body>
   </body>
         
</html>

Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It produces the following result –

JSON – DataTypes



S. No.
Type & Description
1
Number
double- precision floating-point format in JavaScript
2
String
double-quoted Unicode with backslash escaping
3
Boolean
true or false
4
Array
an ordered sequence of values
5
Value
it can be a string, a number, true or false, null etc
6
Object
an unordered collection of key:value pairs
7
Whitespace
can be used between any pair of tokens
8
null
empty

Number
·        It is a double precision floating-point format in JavaScript and it depends on implementation.
·        Octal and hexadecimal formats are not used.
·        No NaN or Infinity is used in Number.
The following table shows the number types –
The following table shows the number types −
S. No.
Type & Description
1
Integer
Digits 1-9, 0 and positive or negative
2
Fraction
Fractions like .3, .9
3
Exponent
Exponent like e, e+, e-, E, E+, E-

 


Syntax


var json-object-name = { string : number_value, .......}

Example
Example showing Number Datatype, value should not be quoted −

var obj = {marks: 97}


String

  • · It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
  • ·        Character is a single character string i.e. a string with length 1.
  • The table shows various special characters that you can use in strings of a JSON document –
S. No.
Type & Description
1
"
double quotation
2
\
backslash
3
/
forward slash
4
b
backspace
5
f
form feed
6
n
new line
7
r
carriage return
8
t
horizontal tab
9
u
four hexadecimal digits

Syntax

var json-object-name = { string : "string value", .......}


Example


Example showing String Datatype −
var obj = {name: 'Amit'}


Boolean

It includes true or false values.

Syntax

var json-object-name = { string : true/false, .......}

Example

var obj = {name: 'Amit', marks: 97, distinction: true}

Array

·        It is an ordered collection of values.
·        These are enclosed in square brackets which means that array begins with .[. and ends with .]..
·        The values are separated by , (comma).
·        Array indexing can be started at 0 or 1.
·        Arrays should be used when the key names are sequential integers.

Syntax

[ value, .......]

 

Example

Example showing array containing multiple objects −
{
   "books": [
      { "language":"Java" , "edition":"second" },
      { "language":"C++" , "lastName":"fifth" },
      { "language":"C" , "lastName":"third" }
   ]
}

Object

·        It is an unordered set of name/value pairs.
·        Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
·        Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).
·        The keys must be strings and should be different from each other.
·        Objects should be used when the key names are arbitrary strings.

Syntax

{ string : value, .......}

 

Example

Example showing Object −
{
   "id": "011A",
   "language": "JAVA",
   "price": 500,
}

Whitespace
It can be inserted between any pair of tokens. It can be added to make a code more readable. Example shows declaration with and without whitespace –

Syntax

{string:" ",....}

 

Example

var obj1 = {"name": "Sachin Tendulkar"}
var obj2 = {"name": "SauravGanguly"}

null

It means empty type.

Syntax

null

 

Example

var i = null;
 
if(i == 1){
   document.write("<h1>value is 1</h1>");
} else{
   document.write("<h1>value is null</h1>");
}

JSON Value

It includes −
  • number (integer or floating point)
  • string
  • boolean
  • array
  • object
  • null

 

Syntax

String | Number | Object | Array | TRUE | FALSE | NULL

 

Example

var i = 1;
var j = "sachin";
var k = null;