JSON Examples

We discussed about Introduction to JSON, JSON Syntax,JSON Datatypes, JSON vs XML (Difference) and JSON Parsing in the previous posts.

If you quickly want to revisit those topics, please click through the below links:


Example 1 – Reading JSON values

<!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":"Krish","lastName":"Ram" },' +
'{"firstName":"John","lastName":"Smith" },' +
'{"firstName":"Subramani","lastName":"Chandran" }]}';

var obj = eval ("(" + txt + ")");

document.getElementById("fname").innerHTML=obj.employees[1].firstName 
document.getElementById("lname").innerHTML=obj.employees[1].lastName 
</script>
</body>
</html>

Demo

First Name:

Last Name:

Example 2 – Reading JSON values

 

<!DOCTYPE html>
<html>
<body>
<script>
var citiesJSON = '{country:[{"city":"Chennai" },{"city":"Delhi" },{"city":"Kolkata" },{"city":"Mumbai"}]}';
var obj = eval ("(" + citiesJSON + ")");
function populateValues(){
var cities = "";
for(var i=0;i<obj.country.length;i++){
cities += "<option>"+obj.country[i].city+"</option>";
}
document.getElementById("cities").innerHTML = cities;
alert("Indian cities has been populated");
}
</script>
<table>
<tr><td>
Country:</td>
<td>
<select onchange="populateValues()">
<option>Select country</option>
<option>India</option>
</select>
</td></tr>
<tr>
<td>
Cities:
</td>
<td>
<select id="cities">
<option>Select city</option>
</select>
</td></tr></table>
</body>
</html>

Demo


Author: admin

Share This Post On
  • rick drolet

    Very well structured and written!

    • admin

      Thanks Rick! :)

  • Shyju C K

    For Example 2, please move the var cities = “”; inside the method populateValues, otherwise the Cities growing on each country change action.

    This is a well documented tutorial. Thanks a lot.

    • admin

      Thanks for noticing it Shyju. :)

Pin It on Pinterest

Shares