JSON is text, written with JavaScript object notation. It is used to transmit data between a server and web application, as an alternative to XML.
Javascript coding with a function is given below to read a text with JSON format, and print it in a table format.
<!DOCTYPE html>
<html>
<body>
<h2>JSON</h2>
<p id="demo"></p>
<script>
var text = '{"mydata":[' +
'{"firstName":"John","lastName":"Doe","age":40 },' +
'{"firstName":"Anna","lastName":"Smith","age":28 },' +
'{"firstName":"Appu","lastName":"Ganesh","age":40 },' +
'{"firstName":"Ganesh","lastName":"Pradhyumn","age":0 },' +
'{"firstName":"Peter","lastName":"Jones","age":30}]}';
function mytable(txt)
{
var mylist,i;
obj = JSON.parse(txt);
mylist="";
mylist="<table border=2 style='border-color:brown; width: 50%;height:16px; '><tr>"
for (x in obj.mydata[0])
{
mylist=mylist+"<th style='padding: 15px;'>" + x +"</th>";
}
mylist=mylist +"</tr>";
for(i=0;i<=obj.mydata.length-1;i++)
{
mylist=mylist+"<tr>";
for (x in obj.mydata[0])
{
myc=eval("obj.mydata[i]." +x)
mylist=mylist+"<td style='padding: 15px;'>";
mylist=mylist+ myc +" ";
mylist=mylist+"</td>";
}
mylist=mylist+"</tr>";
}
mylist=mylist+"</table>";
document.getElementById("demo").innerHTML =mylist;
}
</script>
<div id="mytabdiv">
</div>
<input type="button" name="myc" value="click me" onclick="mytable(text)">
</body>
</html>
Javascript coding with a function is given below to read a text with JSON format, and print it in a table format.
<!DOCTYPE html>
<html>
<body>
<h2>JSON</h2>
<p id="demo"></p>
<script>
var text = '{"mydata":[' +
'{"firstName":"John","lastName":"Doe","age":40 },' +
'{"firstName":"Anna","lastName":"Smith","age":28 },' +
'{"firstName":"Appu","lastName":"Ganesh","age":40 },' +
'{"firstName":"Ganesh","lastName":"Pradhyumn","age":0 },' +
'{"firstName":"Peter","lastName":"Jones","age":30}]}';
function mytable(txt)
{
var mylist,i;
obj = JSON.parse(txt);
mylist="";
mylist="<table border=2 style='border-color:brown; width: 50%;height:16px; '><tr>"
for (x in obj.mydata[0])
{
mylist=mylist+"<th style='padding: 15px;'>" + x +"</th>";
}
mylist=mylist +"</tr>";
for(i=0;i<=obj.mydata.length-1;i++)
{
mylist=mylist+"<tr>";
for (x in obj.mydata[0])
{
myc=eval("obj.mydata[i]." +x)
mylist=mylist+"<td style='padding: 15px;'>";
mylist=mylist+ myc +" ";
mylist=mylist+"</td>";
}
mylist=mylist+"</tr>";
}
mylist=mylist+"</table>";
document.getElementById("demo").innerHTML =mylist;
}
</script>
<div id="mytabdiv">
</div>
<input type="button" name="myc" value="click me" onclick="mytable(text)">
</body>
</html>
No comments:
Post a Comment