Programming
Article
By Craig Buckler

Ajax and Web Service Data Formats Part 2: JSON and JSONP

By Craig Buckler

This is the second article in a series discussing web service data formats for Ajax. In part 1, we examined XML, SOAP and HTML. Today, we take a closer look at JSON and JSONP.

JSON

JavaScript Object Notation was devised by JavaScript guru Douglas Crockford. Essentially, it’s a lightweight data-interchange format written using JavaScript object and array literal syntax.

We can convert the XML books example in the first article to a comparable JSON format:


[
	{
		title: "The Principles of Beautiful Web Design, 2nd Edition",
		url: "http://www.sitepoint.com/books/design2/",
		author: "Jason Beaird",
		publisher: "SitePoint",
		price: {
			currency: "USD",
			amount: 39.95
		}
	},
	{
		title: "jQuery: Novice to Ninja",
		url: "http://www.sitepoint.com/books/jquery1/",
		author: "JEarle Castledine & Craig Sharkie",
		publisher: "SitePoint",
		price: {
			currency: "USD",
			amount: 29.95
		}
	},
	{
		title: "Build Your Own Database Driven Website",
		url: "http://www.sitepoint.com/books/phpmysql4/",
		author: "Kevin Yank",
		publisher: "SitePoint",
		price: {
			currency: "USD",
			amount: 39.95
		}
	}
]

This is an array of books represented as objects with title, url, author, publisher and price properties. Price is a child object with the currency and numeric amount properties.

It’s easy to parse a string of JSON data in JavaScript. Ideally, you can use the browser’s native JSON.parse(json-string) method or a library such as Douglas Crockford’s JSON-js. Even if these are not available, you can fallback to JavaScript’s native eval() function. There’s no parsing code to write and it’s easy to retrieve data:


var json = xhr.responseText;
var book = JSON.parse(json);
alert(book[0].title); // first book title
alert(book[1].url); // second book URL

The advantages of JSON are:

  • A smaller, less verbose format than XML.
  • JSON is generally readable, although it’s best if tabs and carriage returns are used to delimit the data. Unlike XML, browsers do not normally display JSON in a readable format although viewing add-ons are available for Firefox, Chrome and Opera.
  • It’s easy to parse and use JSON data in JavaScript.
  • JSON support is provided in other languages such as PHP.

There are a few disadvantages:

  • JSON has less support than XML in server-side languages, although many third-party libraries are available from the JSON.org website.
  • Security issues can arise if you rely on eval() to parse JSON strings — the payload could contain a malicious script.

However, JSON’s benefits more than outweigh the risks. It’s an ideal Ajax data format is should probably be your first choice.

JSONP (or JSON-P)

If you’re using XMLHttpRequest to call a JSON web service, the response is returned as a string which can be parsed using JSON.parse() or eval(). However, you can also create Ajax components which use script-injection techniques, i.e. a script tag is added to the DOM which loads remote code:


var script = document.createElement("script");
script.src = "http://webservice.com/?a=1&b=2";
document.getElementsByTagName("head")[0].appendChild(script);

Unlike XMLHttpRequest, script injection can retrieve data from remote servers on different domains. This makes the technique ideal for traffic analyzers, bookmarklets, widgets and advertising systems.

Unfortunately, any returned JSON data is executed immediately as native JavaScript code. It’s not assigned to a variable so it’s lost forever. We can overcome this problem by passing the name of a callback function to our web service:


var script = document.createElement("script");
script.src = "http://webservice.com/?a=1&b=2&callback=MyDataHandler";
document.getElementsByTagName("head")[0].appendChild(script);

The web service returns JSON data wrapped in a call to the callback function. This is JSONP, or “JSON with padding,” e.g.


MyDataHandler([
	{
		title: "The Principles of Beautiful Web Design, 2nd Edition",
		url: "http://www.sitepoint.com/books/design2/",
		author: "Jason Beaird",
		publisher: "SitePoint",
		price: {
			currency: "USD",
			amount: 39.95
		}
	}
	...
]);

The JSON object is parsed and passed to the MyDataHandler() function as soon as the download completes.

JSON and JSONP have become popular Ajax data formats. However, it is possible to reduce the data size even further — we’ll discuss the options in the final post in this series.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account