Learn to create a simple object using – Json

0
2810

In this session today we will study the Json fundamentals in which we will learn to create an object using json.

  • So to create an object using json follow the steps given below :

  1. Create a new folder on the desktop for example Json :

  2. Inside this folder create a new file say index.html.
  3. Right click on index.html and open it with notepad++ , the window look like as shown below:-

  4. Write the following code in the index.html file to create a json object.

    <html>
    <head>
    <title>Creating Object JSON with JavaScript</title>
    <script language="javascript" >
     var JSONObj = { "name" : "www.eduonix.com/blog", "year" : 2013 };
     document.write("<h1>JSON with JavaScript example</h1>");
     document.write("<br>");
     document.write("<h3>Website Name="+JSONObj.name+"</h3>"); 
     document.write("<h3>Year="+JSONObj.year+"</h3>"); 
    </script>
    </head>
    <body>
    </html>
    
  5. After writting the code your Notepad++ window will have the following look:-

  6. Now run it on the browser and youw will get the output as shown below :

  7. Let’s take some another example for creating a json object,so write the given code in Notepad++.

    <!DOCTYPE html>
    <html>
    <body>
    <h2>Create Object from JSON String</h2>
    <p>
    First Name: <span id="fname"></span><br> 
    Last Name: <span id="lname"></span><br> 
    </p> 
    <script>
    var txt = '{"employees":[' +
    '{"firstName":"Scott","lastName":"Darj" },' +
    '{"firstName":"Smith","lastName":"Anderson" },' +
    '{"firstName":"John","lastName":"Jones" }]}';
    
    var obj = eval ("(" + txt + ")");
    
    document.getElementById("fname").innerHTML=obj.employees[1].firstName 
    document.getElementById("lname").innerHTML=obj.employees[1].lastName 
    </script>
    </body>
    </html>
    
  8. Notepad++ window will have the following look after writing the code:-

  9. After running it on the browser you will get the following output :

  10. Thus we have successfully created a simple object using json.

LEAVE A REPLY

Please enter your comment!
Please enter your name here