A JSON Tutorial

Welcome to JavaScript XML, home to all of the JavaScript, programming, XML, and JSON examples and source code you need. Just quality content - and 100% free!

All source code on this website is released under the MIT License.

To learn about my other projects, please visit my blog at http://fonte.me

Privacy Policy

A JSON Tutorial

JavaScript Object Notation is a data format used for transporting data between and within applications, and at this point, many programming languages, environments, and frameworks support it. Whether you're using JavaScript, jQuery, PHP, or VB, there's going to be some form of JSON support.

The idea behind JSON is simple: represent data as JavaScript objects. This sometimes requires a bit of thoughtful planning, but for the most part, JSON data structures are intuitive to anyone familiar with object-oriented programming, or even the use of C structs. A strong understanding of the method/behavior side of OOP is not required - JSON is really only concerned with the “state” side of objects, which is all conventional JavaScript objects really are.

Here’s a simple example of a JSON file:

        	
{
	“customers”: [
		“Bob”,
		“Joe”,
		“Jill”
	]
}
			
		

Notice how both the keys (just one in this case, “customers”) and the values (Bob, Joe, and Jill) are enclosed in double quotes. This is required for all JSON documents; unless the value is a number or a Boolean value, it must be enclosed in double quotes; numbers and Boolean values may be enclosed in double quotes as well.

Here is an example showing all of the major data types JSON can represent, namely, strings, numbers, Boolean values, objects, arrays, and null:

        	
{
	“computer”: {
		“cpu”: “i7”,
		“drives”: [
			“500GB HD”,
			“128GB SSD”,
			“Optical Drive”
		],
		“hasBattery”: false,
		“Manufacture Year”: 2010,
		“Current Sale Price”: null
	}
}
			
        

Originally, AJAX was only capable of transferring XML from the server to the client. Now, AJAX-like functionality is available for JSON data as well. Libraries such as jQuery and the Dojo Toolkit support JSON AJAX requests.

One particularly interesting AJAX technology is JSONP, that is, JSON with Padding. This allows cross-domain AJAX requests. What actually happens is the JSON file is retrieved as a script from another domain, and then injected or “eval”-ed into the page. JSONP is particularly well-suited for creating mash-ups of various sites’ content.

I hope this tutorial has proved useful for you. To learn more about JSON/JSONP AJAX requests, check out the “AJAX Libraries” section of the web page.