Handling JSON Object Using Simple JavaScript

Handling JSON Object Using Simple JavaScript

In this article, I will be explaining about how to read Json object using simple javascript. After reading this article , you will be able to understand

  1. What is JSON
  2. How to read Json Using JavaScript

Let's Start first with gettting few details about JSON .

What is JSON

  1. JSON is a file format used to store information in an organized and easy-to-access manner.
  2. Its full form is JavaScript Object Notation.
  3. It offers a human-readable collection of data that can be accessed logically. Its filename extension for written programming code is .json.
  4. The Internet media type for JSON is application/json, and its Uniform Type Identifier is public.json.

Rules for JSON Syntax

 1.  Data should be in name/value pairs
 2.  Data should be separated by commas
 3. Curly braces should hold objects
 4. Square brackets hold arrays

I will create a separate blog on JSON in which we will be discussing about why we use JSON, JSON Vs XML, History of JSON etc.

How to Read JSON Object Using Simple JavaScript

Now Let's start the blog of reading JSON File using Simple Javascript

Let’s take a scenario where we have to read a collection of few employees and each employee has few fields i.e. firstName, lastName and age. In below step by step solution, I will be providing you how to declare JSON, read JSON, write these details to HTML Div. using JavaScript.

If you follow steps mentioned here, then you will be able to understand how easy to use JSON for reading data from JSON, writing data to JSON.

Step 1

Create a HTML file name “JsonSample.html” and take three controls i.e. div to print the values of the employee field i.e. firstName, lastName and age.

<!DOCTYPE html>
<html>
<head>
    <title>Json Sample</title>
</head>
<body onload="onloadBody();">
    <table border="1">
        <tr>
            <td colspan="3">Employee Details</td>
        </tr>
        <tr>
            <td>First Name</td>
            <td>Last Name</td>
            <td>Age</td>
        </tr>
        <tr>
            <td><div id="firstName"></div></td>
            <td><div id="lastName"></div></td>
            <td><div id="age"></div></td>
        </tr>
    </table>
</body>
</html>

Step2: - Lets just define the employee collection in Json inside JavaScript.

For defining JavaScript, we have to add <script> tag inside html or a separate .js file.

<script type="text/javascript">
        // This is how we can create collection to store the values of employees.
        var employees = [
            {
                firstName: "Dhiraj",
                lastName: "Kumar",
                age: 35
            },
            {
                firstName: "Paresh",
                lastName: "Kale",
                age: 30
            },
            {
                firstName: "Jivan",
                lastName: "Gulhane",
                age: 32
            },
            {
                firstName: "Rupesh",
                lastName: "Patil",
                age: 31
            }
        ];

    </script>

Step 3: - Now we will write on JavaScript function to get these json values and write into the div created in html page (Step 1).

We will create one Method BodyOnLoad which will be called on OnLoad method of body.

<script type=”text/javascript”>
function BodyOnLoad()
{
//code for reading json and writing to div in html
}
</script>

In body tag , this method will trigger on Onload event. <body OnLoad=”BodyOnLoad()”>

Step 4: - Now code need to be written inside JavaScript function to read json and write to the div.

<script>
  function BodyOnLoad()
        {
          //Reading Json File and getting first employee first name
          var firstEmployeeFirstName= employees[0].firstName;
          //Reading Json File and getting first employee last name
          var lastEmployeeLastName= employees[0].lastName;         
           //Reading Json File and getting first employee age
          var firstEmployeeAge= employees[0].age;

            var firstnameelement = document.getElementById("firstName");
            firstnameelement.innerHTML = firstEmployeeFirstName;

            var lastElement = document.getElementById("lastName");
            lastElement.innerHTML = lastEmployeeLastName;

            var ageElement = document.getElementById("age");
            ageElement.innerHTML = firstEmployeeAge;

        }
</script>

Step 5: - After adding all the above code, HTML file will be as below

<!DOCTYPE html>
<html>
<head>
    <title>Json Sample</title>
    <script type="text/javascript">
        // This is sample json file which is written here to store the values of employees.
        var employees = [
            {
                firstName: "Dhiraj",
                lastName: "Kumar",
                age: 35
            },
            {
                firstName: "Paresh",
                lastName: "Kale",
                age: 30
            },
            {
                firstName: "Jivan",
                lastName: "Gulhane",
                age: 32
            },
            {
                firstName: "Rupesh",
                lastName: "Patil",
                age: 31
            }
        ];
        //This function is used to call when body of this page is loaded.
        function BodyOnLoad() {
            //Reading Json File and getting first employee first name
            var firstEmployeeFirstName = employees[0].firstName;
            //Reading Json File and getting first employee last name
            var lastEmployeeLastName = employees[0].lastName;
            //Reading Json File and getting first employee age
            var firstEmployeeAge = employees[0].age;

            var firstnameelement = document.getElementById("firstName");
            firstnameelement.innerHTML = firstEmployeeFirstName;

            var lastElement = document.getElementById("lastName");
            lastElement.innerHTML = lastEmployeeLastName;

            var ageElement = document.getElementById("age");
            ageElement.innerHTML = firstEmployeeAge;

        }


    </script>
</head>
<body onload="BodyOnLoad();">
    <table border="1">
        <tr>
            <td colspan="3">Employee Details</td>
        </tr>
        <tr>
            <td>First Name</td>
            <td>Last Name</td>
            <td>Age</td>
        </tr>
        <tr>
            <td><div id="firstName"></div></td>
            <td><div id="lastName"></div></td>
            <td><div id="age"></div></td>
        </tr>
    </table>
</body>
</html>

Now if you open this HTML file , it will be look like as below

output.png

Happy Reading!!!! Please write feedback and your reviews. Also you can connect with me on twitter @ twitter.com/CodeAsItIs1 or Instagram - instagram.com/CodeAsItIs

Thanks and regards,

Dhiraj Kumar