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.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

</head>

<body>

    <form id="form1" runat="server">

    <script>

        var student = {

            name: "Rama Sagar",

            branch: "computers",

            hometown: "Hyderabad",

            interestIn: "C#"

        }

        document.write("Name:-" + student.name + "<br>");

        document.write("branch:- " + student.branch + "<br>");

        document.write("hometown:-" + student.hometown + "<br>");

        document.write("Interest In:- " + student.interestIn + "<br>");

    </script>

    </form>

</body>

</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 (').
 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

</head>

<body>

    <form id="form1" runat="server">

    <script>

        var student = '{"name":"Rama Sagar" , "branch": "computers", "hometown":"Hyderabad", "interestIn": "C#"}';

        //JSON.parse method to parse json data

        var value = JSON.parse(student);

        document.write("Name:-" + value.name + "<br>");

        document.write("branch:- " + value.branch + "<br>");

        document.write("hometown:-" + value.hometown + "<br>");

        document.write("Interest In:- " + value.interestIn + "<br>");

    </script>

    </form>

</body>

</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.

Up Next
    Ebook Download
    View all
    Learn
    View all