JSON

Contact Us or call 1-877-932-8228
JSON

JSON

JSON is a lightweight format for exchanging data between the client and server. It is often used in Ajax applications because of its simplicity and because its format is based on JavaScript object literals.

Take a look at this plain text page:

Code Sample:

QuickRecap/Demos/json.txt
{
	"1" : {
		"name" : "Montgomery Burns"
	},
	"35739" : {
		"name" : "Homer Simpson",
		"reportsTo" : 1
	}
}

The file above uses JSON syntax to hold employee records. Now imagine that the file was generated dynamically using a call to a database that retrieved all the employees from our company and marked them up in a similar way. We could use Ajax to grab and query that data. Here is a simple example:

Code Sample:

QuickRecap/Demos/json.html
---- C O D E   O M I T T E D ----

<script type="text/javascript">
function showBoss(badgeNo) {
	var ajax = new XMLHttpRequest();
	var employees;
	ajax.open("GET", "json.txt", true);
	ajax.onreadystatechange = function() {
		if ( this.readyState > 2 && typeof employees == "undefined" ) {
			document.getElementById("output").innerHTML = this.responseText;
			employees = JSON.parse(this.responseText);
			alert(employees[employees[badgeNo].reportsTo].name);
		}
	}
	ajax.send();
}
</script>
</head>
<body>
<button onclick="showBoss(35739)">Show Homer's Boss</button>
<pre id="output"></pre>
---- C O D E   O M I T T E D ----

Note that, like with xmlhttprequest.html, this code must also run through a web server (e.g, http://localhost/JavaScript/ClassFiles/QuickRecap/Demos/json.html).

Pre-HTML5, the XMLHttpRequest and JSON objects were not part of the official HTML specification. In HTML5, however, they are.

For a deeper review of how JSON works in JavaScript, see JSON in JavaScript.

Next