Friday, August 30, 2013

Simple JSON Example

Simple JSON example

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
body{
    font-size: 12px; font-family: sans-serif;
}
</style>
</head>

<body>

<h3>Employee Details</h3>
<p>First Name: <span id="fname"></span></p>
<p>Last Name: <span id="lname"></span></p>
<p>Age: <span id="age"></span></p>
<h3>Address</h3>
<p>Address : <span id="address1"></span></p>
<p>Street : <span id="address2"></span></p>
<p>City : <span id="city"></span></p>
<p>Country : <span id="country"></span></p>
<h3>Department Information</h3>
<p>Department Name : <span id="deptname"></span></p>
<p>Job Role : <span id="jrole"></span></p>
<p>Designation : <span id="desig"></span></p>

<script>
var employees = [
{ "firstName" : "Sanjeeva" , "lastName" : "Pathirana" , "age" : 30 },
{ "firstName" : "Sandamali" , "lastName" : "Silva" , "age" : 25 },
{ "firstName" : "Thinuli" , "lastName" : "Pathirana" , "age" : 20 }];

document.getElementById("fname").innerHTML= employees[0].firstName;
document.getElementById("lname").innerHTML= employees[0].lastName;
document.getElementById("age").innerHTML= employees[0].age;

var addressVar = '{"address":[' +
'{"add1":"126 B","add2":"Pubudu Uyana", "city" : "Piliyandala" , "country" : "Sri Lanka" }' +
']}';

var addressObj = eval ("(" + addressVar + ")");

document.getElementById("address1").innerHTML=addressObj.address[0].add1;
document.getElementById("address2").innerHTML=addressObj.address[0].add2;
document.getElementById("city").innerHTML=addressObj.address[0].city;
document.getElementById("country").innerHTML=addressObj.address[0].country;

var JSONObject = {
     "department":"Information Technology",
     "role":"Team Lead",
     "designation":"Software Engineer"
};
document.getElementById("deptname").innerHTML=JSONObject.department;
document.getElementById("jrole").innerHTML=JSONObject.role;
document.getElementById("desig").innerHTML=JSONObject.designation ;
</script>

</body>
</html>

Out put as follows :