Home Web Programming Tutorials Learn to create a simple object using – Json

Learn to create a simple object using – Json

0
3104

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. v1

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

  6. 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>
    
  7. After writting the code your Notepad++ window will have the following look:-
  8. v3

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

  11. 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>
    
  12. Notepad++ window will have the following look after writing the code:-
  13. v5

  14. After running it on the browser you will get the following output :
  15. v6

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

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Become An Insider!

Discover latest news, tech updates, fresh 
arrivals, sale announcements and exciting offers!
I'm In!
Hurry up! Offer valid till stocks last.
close-link