Introduction To JSON

Introduction To JavaScript Object Notation (JSON)
 
The following describes JSON:
  • JSON is a lightweight data-interchange format.
  • JSON is a self-describing and easy to understand and easier to use alternative to XML.
  • JSON is language-independent.
The following are some rules of JSON Syntax:
  • JSON data consists of name/value pairs.
  • In JSON data is separated by commas.
  • In JSON Curly Braces hold objects.
  • In JSON Square Braces hold arrays.
JSON Data Syntax
JSON data consist of name and value pairs. It consists of a field name in double quotes (""), then a colon then a value.
 
JSON values can be a number, a string, a Boolean, an array, an object or null.
 
Syntax Of JSON Objects

JSON objects can contain multiple name/values pairs written inside Curly Braces.
 
Syntax Of JSON Arrays

A JSON array can contain multiple objects and are written inside Square Braces.
 
In this example, the object "students" is an array containing three objects. Each object is a record of a student.
 
Example: JSON Object Creation in JavaScript. 
  1. <!DOCTYPE html>  
  2. <html>  
  3.    <body>  
  4.       <h2>JSON Object Creation</h2>  
  5.       <p id="Result"></p>  
  6.   
  7.       <script>  
  8.          var obj = JSON.parse('{"Company_Name":"C-SharpCorner","Address":"Noida","phone":"XXXXXX"}');  
  9.   
  10.          document.getElementById("Result").innerHTML =  
  11.          obj.Company_Name+ "<br>" +  
  12.          obj.Address+ "<br>" +  
  13.          obj.phone;  
  14.       </script>  
  15.     
  16.    </body>  
  17. </html>  
The following is the output of that:
 
 
 
XML has to be parsed with an XML parser, whereas JSON can be parsed by a standard JavaScript function.
 
The following is an XML example of student objects with 3 student records:
  1. <students>  
  2.     <student>  
  3.         <firstName>Shalin</firstName> <lastName>Dashora</lastName>  
  4.     </student>  
  5.     <student>  
  6.         <firstName>Milan</firstName> <lastName>Jain</lastName>  
  7.     </student>  
  8.     <student>  
  9.         <firstName>Priyanshi</firstName> <lastName>Dashora</lastName>  
  10.     </student>  
  11. </students>  
Similarities and Differences between JSON and XML

Similarity
  • Both JSON and XML are self describing.
  • Both JSON and XML are hierarchichal.
  • Both JSON and XML can be parsed and used by many programming languages.
  • Both JSON and XML can be fetched with an XMLHttpRequest.
 Differences
  • JSON doesn't use an end tag.
  • JSON is shorter.
  • JSON is quicker to read and write.
  • JSON can use arrays.
  • JSON is faster and easier, for AJAX applications.
  • XML Extracts values and stores them in variables.
  • JSON parses JSON strings.

Up Next
    Ebook Download
    View all
    Learn
    View all