Json - Json From String Part-1


Json - Create Json From String Part-1

  • JSON is a subset of JavaScript. Both follows the same syntax.
  • JavaScript function JSON.Parse(text) is used to convert a JSON text into a JavaScript object.

Sample Code :

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

Code Explanation :

    <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 header for JSON data is declared as "employees".

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

    {
        "firstName":"venkat",
        "lastName":"jayaka"

    },

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

    {
        "firstName":"jln",
        "lastName":"jayaka"

    },

    The code obj = JSON.parse(WikiTechy_employees); parses the JSON variable “WikiTechy_employees” into a javascript object.

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

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

    The code obj.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 obj.employees[1].firstNameaccess the “firstname” attribute from the second record of the JSON object.

    The code obj.employees[1].lastNameaccess 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.