Json -Json From String Part-2


Json - Create Json From String Part-2

eval() :eval() is a substitute for JSON.parse() function 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>
        var WikiTechy_employees = 
            '{"employees":[' +
            '{"firstName":"venkat","lastName":"jayaka" },' +
            '{"firstName":"jln","lastName":"jayaka" }]}';   
        obj=  eval ("(" + WikiTechy_employees + ")");
        document.getElementById("WikiTechy_ParagraphTag").innerHTML =
            "First Employee is :" + obj.employees[0].firstName + " " 
            + obj.employees[0].lastName
            +"</br></br>" +        
            "Second Employee is :" + obj.employees[1].firstName + " " 
            + obj.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 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 = eval(“(“ + WikiTechy_employees + “)”); evaluates 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 output from the <h1> is displayed in the browser as WikiTechy - learn json basics - json step by step tutorials.

    The first employee record is displayed as First Employee is : venkat jayaka

    The second employee record is displayed as Second Employee is : jln jayaka