Simon Willison’s Weblog

Subscribe

JSON and Yahoo!’s JavaScript APIs

16th December 2005

I had the pleasure yesterday of seeing Douglas Crockford speak about JSON, the ultra-simple data interchange format he has been promoting as an alternative to XML. JSON is a subset of JavaScript, based around that language’s array, string and object literal syntax.

As of today, JSON is supported as an alternative output format for nearly all of Yahoo!’s Web Service APIs. This is a Really Big Deal, because it makes Yahoo!’s APIs available to JavaScript running anywhere on the web without any of the normal problems caused by XMLHttpRequest’s cross domain security policy.

Like JSON itself, the workaround is simple. You can append two arguments to a Yahoo! REST Web Service call:


&output=json&callback=myFunction

The page returned by the service will look like this:


myFunction({ JSON data here });

You just need to define myFunction in your code and it will be called when the script is loaded. To make cross-domain requests, just dynamically create your script tags using the DOM:


var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '...' + '&output=json&callback=myFunction';
document.getElementsByTagName('head')[0].appendChild(script);

In long running apps you’ll want to work out some kind of cleanup system to remove script tags from the DOM once they have been executed. More on this technique here.

It should be noted that del.icio.us has had APIs like this for a while.

This is JSON and Yahoo!’s JavaScript APIs by Simon Willison, posted on 16th December 2005.

Next: Get tickets for filming of Jools Holland's TV show

Previous: Don't be eval()

Previously hosted at http://simon.incutio.com/archive/2005/12/16/json