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 :
- Create a new folder on the desktop for example Json :
- Inside this folder create a new file say index.html.
- Right click on index.html and open it with notepad++ , the window look like as shown below:-
- 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>
- After writting the code your Notepad++ window will have the following look:-
- Now run it on the browser and youw will get the output as shown below :
- 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>
- Notepad++ window will have the following look after writing the code:-
- After running it on the browser you will get the following output :
- Thus we have successfully created a simple object using json.