Json - Basic Program


Json - Basic Program

Sample Code :

<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue">WikiTechy - learn json basics - json step by step</h1>
</br>
<h2 id="WikiTechy_ParagraphTag"  style="color:green"></h2>
<script>
varWikiTechy_employees = [
        {
        "firstName":"venkat",
        "lastName":"jayak"
        }, 
        {
        "firstName":"jln",
        "lastName":"jayak"
        }     
    ];
 document.getElementById("WikiTechy_ParagraphTag").innerHTML =
       "First Employee is :" + WikiTechy_employees[0].firstName + " " + WikiTechy_employees[0].lastName
        + "</br></br></br>"
     + "Second Employee is :" + WikiTechy_employees[1].firstName + " " +  WikiTechy_employees[1].lastName;        
</script>
</body>
</html>

Code Explanation :

   A <h2>heading element is declared with the id “WikiTechy_ParagraphTag” to appear in green colored text.

   The <script>element is initiated to enter JSON code.

   The variable “WikiTechy_employees” is declared to contain JSON data.

    The first record of JSON data contains a firstname and lastname as follows:

  {		
        "firstName":"venkat",
        "lastName":"jayak"

        },

   The second record of JSON data contains a firstname and lastname as follows:

        {
        "firstName":"jln",
        "lastName":"jayak"

        }     

    The JSON data declaration is completed with the symbol ];

    The code document.getElementById("WikiTechy_ParagraphTag") accesses the <h2>element, declared previously by its id “WikiTechy_ParagraphTag”.

    The code WikiTechy_employees[0].firstNameaccess the “firstname” attribute from the first record of the JSON object.

    The code WikiTechy_employees[0].lastNameaccess the “lastname” attribute from the first record of the JSON object. Both these values are assigned to the “innerHtml” attribute of the <h2>element id “WikiTechy_ParagraphTag".

    The code WikiTechy_employees[1].firstNameaccess the “firstname” attribute from the second record of the JSON object.

    The code WikiTechy_employees[1].lastName; access the “lastname” attribute from the second record of the JSON object. Both these values are appended to the existing data of “innerHtml” attribute of the <h2>element id “WikiTechy_ParagraphTag".

    The JSON code is completed with script ending element as </script>.

Sample Output :

  • The <h2> element is printed with data from the first record and second record of the employees table as shown above.