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.
More recent articles
- Teresa T is name of the whale in Pillar Point Harbor near Half Moon Bay - 8th September 2024
- Calling LLMs from client-side JavaScript, converting PDFs to HTML + weeknotes - 6th September 2024
- Building a tool showing how Gemini Pro can return bounding boxes for objects in images - 26th August 2024