Introduction to JSON

JSON stands for JavaScript Object Notation. JSON is a light-weight data interchange format that uses JavaScript syntax in text format that can be read and used as data by other programming languages.

In this example, we will use JSON to define an object with an array of records – we will use the Avengers characters for this example. Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>JSON</title>
</head>
 
<body>
<h2>The Avengers</h2>
 
<p id="avengerstext"></p>
 
<script>
var text='{"avengers":['+
'{"firstName":"Bruce","lastName":"Banner"},'+
'{"firstName":"Tony","lastName":"Stark"},'+
'{"firstName":"Natalia","lastName":"Romanova"},'+
'{"firstName":"Thor","lastName":"Odinson"}]}';
 
obj = JSON.parse(text);
document.getElementById("avengerstext").innerHTML=obj.avengers[0].firstName+" "+obj.avengers[0].lastName+"<br>"+obj.avengers[1].firstName+" "+obj.avengers[1].lastName+"<br>"+obj.avengers[2].firstName+" "+obj.avengers[2].lastName+"<br>"+obj.avengers[3].firstName+" "+obj.avengers[3].lastName;
 
</script>
 
</body>
</html>