JSON in JavaScript

Introduction

 
In this article, we will understand JSON data objects in JavaScript. In JavaScript, the normal data (in the form of a class) and JSON are both treated as an object and using the property of object we can extract values.
 
In the following example let us define one simple data object and using the property of that we will access the value. The representation of the data is very much similar to a JSON data format.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>  
  8.         var student = {  
  9.             name: "Rama Sagar",  
  10.             branch: "computers",  
  11.             hometown: "Hyderabad",  
  12.             interestIn: "C#"  
  13.         }  
  14.         document.write("Name:-" + student.name + "<br>");  
  15.         document.write("branch:- " + student.branch + "<br>");  
  16.         document.write("hometown:-" + student.hometown + "<br>");  
  17.         document.write("Interest In:- " + student.interestIn + "<br>");  
  18.     </script>  
  19.     </form>  
  20. </body>  
  21. </html>    
Output
 
data object
 
Now let us see the JSON data. We are representing the same data in true JSON format. We are putting an entire data string within single quotes (').
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <script>  
  8.         var student = '{"name":"Rama Sagar" , "branch": "computers", "hometown":"Hyderabad", "interestIn": "C#"}';  
  9.         //JSON.parse method to parse json data  
  10.         var value = JSON.parse(student);  
  11.         document.write("Name:-" + value.name + "<br>");  
  12.         document.write("branch:- " + value.branch + "<br>");  
  13.         document.write("hometown:-" + value.hometown + "<br>");  
  14.         document.write("Interest In:- " + value.interestIn + "<br>");  
  15.     </script>  
  16.     </form>  
  17. </body>  
  18. </html>  
Output
 
JSON data
 

Summary

 
In this article, we learned about the JSON/object in JavaScript. In a future article, we will learn more basic concepts of JavaScript.

Recommended Ebook

Voice of a Developer: JavaScript From Scratch

Download Now!
Similar Articles