An increasingly popular alternative to XML is JSON (JavaScript Object Notation). It is a simplistic text-based format that is designed to be human readable. Unlike XML, it has no notion of namespaces and can only represent data in the format of associative arrays.
All Data APIs support JSON output through the use of the alt
parameter. For example, you can retrieve the current most popular videos from YouTube in JSON format as follows:
http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?v=2&alt=json
When you are working with JavaScript, you can avoid crossdomain restrictions by loading results from the Data API through a <script>
tag with a custom callback. To do this you set the alt
parameter to have the value json-in-script
and also use the callback
parameter to identify what JavaScript function should be called once the results have been loaded.
A simple example is retrieving all of the uploads for a particular user, in this case 'GoogleDevelopers':
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?v=2&alt=json-in-script&format=5&callback=showMyVideos"> </script>
The v
parameter ensures we are using Version 2 of the API. The format
parameter ensures we are only retrieving videos that can be embedded in an external webpage. The callback
parameter is specifying showMyVideos
as the function to execute once the results are returned. This function could look something like:
function showMyVideos(data) { var feed = data.feed; var entries = feed.entry || []; var html = ['<ul>']; for (var i = 0; i < entries.length; i++) { var entry = entries[i]; var title = entry.title.$t; html.push('<li>', title, '</li>'); } html.push('</ul>'); document.getElementById('videos').innerHTML = html.join(''); }
This code inserts an unordered list of videos into a <div> (or other block-level element) with the id of "videos" on the page. Each list item will be the video's title.
Of course there is much more you can do, such as showing a thumbnail for the video or using it with our Player APIs. For more examples and code check out the YouTube JSON codelab.