JSON AND OBJECT LITERALS

JSON – JAVASCRIPT OBJECT NOTATION JSON is INSPIRED by JAVASCRIPT OBJECT LITERALS And it LOOKS like JAVASCRIPT OBJECT LITERALS But JSON and OBJECT LITERALS are TWO DIFFERENT THINGS In PREVIOUS [...]

JSON – JAVASCRIPT OBJECT NOTATION

  • JSON is INSPIRED by JAVASCRIPT OBJECT LITERALS
  • And it LOOKS like JAVASCRIPT OBJECT LITERALS
  • But JSON and OBJECT LITERALS are TWO DIFFERENT THINGS
  • In PREVIOUS YEARS DATA was SENT OVER the INTERNET in VARIOUS FORMATS
  • And XML was the MOST PREFERRED FORMAT

EXAMPLE OF XML

< object >

< fname> Samaresh </fname>

<lname> Bisoi </lname>

</object >

  • In the XML FORMAT TAGS SURROUNDING the DATA
  • The SERVER get this DATA and was ABLE to PARSE it out

PROBLEM WITH THE XML FORMAT WAS THE DOWNLOAD TIME

  • Tags are UNNECESSSARY CHARACTERS
  • HUGE unnecessary WASTAGE of DOWNLOAD BANDWITH if you are DEALING with LOTS of DATA
  • Just to SEND one PIECE of DATA , I am SENDING the PROPERTY NAME TWICE
  • So WHAT PEOPLE did , they LOOKED at JAVASCRIPT OBJECT NOTATION
  • And DECIDED make STRING that LOOKS SOMETHING like this 

{ fname : ‘ Samaresh ‘ , lname : ‘ Bisoi’ }

  • Now a days we SEND DATA over INTERNET using JSON FORMAT
  • Its just a STRING of DATA but it LOOKS like OBJECT LITERAL SYNTAX EXCEPT with SOME DIFFERENCE 

In JSON FORMAT PROPERTIES has to be WRAPPED in QUOTES

{ “fname” : ” Samaresh” , “lname” : ” Bisoi ” }

// This is also a VALID OBJECT LITERAL SYNTAX

  • JSON is TECHNICALLY a SUBSET of OBJECT LITERAL SYNTAX
  • ANYTHING that is JSON VALID is VALID in OBJECT LITERAL SYNTAX but the OPPOSITE is NOT TRUE.
  • JSON is NOT REALLY a PART of JAVASCRIPT but because its so EASY and POPULAR , JAVASCRIPT comes with SOME BUILT in FUNCTIONALITY to TRANSFER between the TWO.

CONVERT OBJECT INTO JSON STRING

TO SEND AN OBJEC TO A SERVER CONVERT IT INTO JSON STRING 

var objectLiteral = { 

fname : ” Samaresh “,

lname : ” Bisoi “

console.log( JSON.stringify(objectLiteral) );

// This will CONVERT the OBJECT into a JSON STRING and SEND to the SERVER as BELOW

“fname ” : ” Samaresh “,

“lname” : ” Bisoi” 

}

CONVERT JSON STRING INTO AN OBJECT

ACCEPTING JSON STRING FROM THE SERVER AND  CONVERT IT INTO AN OBJECT 

var jsonValue = 

JSON.parse(  ‘  { ” fname” : ” Samaresh ” , “lname” : ” Bisoi ” } );

console.log(jsonValue);

// This will CONVERT the JSON STRING into an OBJECT which can be PARSE to the BROWSER.

Leave your comment

Please enter your name.
Please enter comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.