Share via


Parsing JSON results

As aforementioned, Bing API can return results in multiple protocols, or media types. Besides XML, the other media type you can request is application/json - JavaScript Object Notation (JSON).

JSON is a serialization format for data that has become popular for two reasons:

  • JSON has a smaller serialization size than XML and represents a saving of network bandwidth, as well as of serialization/deserialization costs.

  • Second, JSON is a more natural format than XML with which to work when building AJAX applications using JavaScript. (This is because XML processing in most JavaScript implementations isn’t very sophisticated).

The principles discussed in the previous sections with respect to sending a request to the XML interface are all applicable to sending a request to the JSON interface. However, processing the results from the JSON interface is different than processing results the XML interface returns.

The same main query we’ve used in previous sections, when sent to the JSON interface, might produce the results in Example 1.

Example 1: JSON Serialized Response

"SearchResponse":{ "Version":"2.0","Query":{ 
"SearchTerms":"sushi"},"Web":{ "Total":15000000,"Offset":0,"Results":[ 
{ "Title":"Sushi - Wikipedia, the free encyclopedia","Description":"In 
Japanese cuisine, sushi (寿司, 鮨, 鮓, sushi?) is vinegared rice, usually 
topped with other ingredients, including fish (cooked or uncooked) and 
vegetables.","Url":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DisplayUrl
":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DateTime":"2008-06-
09T06:42:34Z"}]}} /* pageview_candidate */}

The full URL for this query would be http://api.search.live.net/json.aspx?Appid=<AppID>&query=sushi&sources=web.

This would be the query we’d run if we wanted to process the JSON-encoded result from a program that was not running inside of a browser (for an example of this scenario, see ). In many cases, when we use the JSON interface, we want the query to be executed from a browser and the results displayed for the use of an AJAX application (running in a browser). Note that JSON serialization is supported by other runtimes and languages, such as PHP and Ruby.

In order to get the JSON result into the browser, we are going to have to add a script tag into our HTML page dynamically. This is necessary because browsers will not let you use JSON results from another website due to security restrictions. AJAX applications can only invoke URLs from the site from which the AJAX application was downloaded. Because our AJAX application can’t be uploaded to http://api.search.live.net, we must use this alternate mechanism to use the JSON interface. We will add a script tag to the page dynamically using JSONP.

JSONP is a technique for injecting JavaScript from another website into a browser. Adding a script element (with its src attribute pointing to the json.aspx URL) causes the browser to send a request to Bing. Bing will return JavaScript dynamically to the page. The JavaScript injected into the page will call a method with the JSON-encoded results, the name of the method having been passed as the value of the JSONCallback query string parameter. The JsonType query string parameter is also passed in this case with the value of callback.

Assuming the correct HTML page is running in the browser with an input element of typewho text that has an id attribute value of searchText, and a ul element that has an who attribute value of resultList, the JavaScript in Example 2 would dynamically add a script tag to the head tag (the proper place for a script tag). This will cause the browser to, on demand, request the Bing API Version 2.0 JSON interface. The searchDone function is the name passed as the JSONCallback parameter. Example 2 shows how this JavaScript might look.

Example 2: Brower JavaScript code for JSONP

function search() {
          var search = "&query=" + document.getElementById("searchText").value;
          var fullUri = serviceURI + AppId + search;
          var head = document.getElementsByTagName('head');
          var script = document.createElement('script');
          script.type = "text/javascript";
          script.src = fullUri;
          head[0].appendChild(script);
       }
       function searchDone(results) {
           var result = null;
           var parent = document.getElementById('resultList');
           parent.innerHTML = '';
           var child = null;
           for (var i = 0; i < results.SearchResponse.Image.Results.length; i++) {
               result = results.SearchResponse.Image.Results[i];
               child = document.createElement('li');
               child.className =  "resultlistitem";
               child.innerHTML = '<a href="' + result.Url +'"><img src="' + result.Thumbnail.Url +'" alt="' + result.Title +'" /></a>';
               parent.appendChild(child);
           }
      }

Example 3: JSONP Callback Code

if(typeof searchDone == 'function') searchDone({ "SearchResponse":{ 
"Version":"2.0","Query":{ "SearchTerms":"sushi"},"Web":{ 
"Total":15000000,"Offset":0,"Results":[ { "Title":"Sushi - Wikipedia, 
the free encyclopedia","Description":"In Japanese cuisine, sushi (寿司, 
鮨, 鮓, sushi?) is vinegared rice, usually topped with other 
ingredients, including fish (cooked or uncooked) and 
vegetables.","Url":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DisplayUrl
":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DateTime":"2008-06-
09T06:42:34Z"}]}} /* pageview_candidate */});

The full code for this page is in Example 4.

Example 4: Full JSONP HTML Page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

     <link href="styles.css" rel="stylesheet" type="text/css" />
    <title>Using Bing and JSON</title>
    <script type="text/javascript">
        function search() {
            var search = "&query=" + document.getElementById("searchText").value;
            var fullUri = serviceURI + AppId + search;
            var head = document.getElementsByTagName('head');
            var script = document.createElement('script');
            script.type = "text/javascript";
            script.src = fullUri;
            head[0].appendChild(script);
         }
         function searchDone(results) {
             var result = null;
             var parent = document.getElementById('resultList');
             parent.innerHTML = '';
             var child = null;
             for (var i = 0; i < results.SearchResponse.Image.Results.length; i++) {
                 result = results.SearchResponse.Image.Results[i];
                 child = document.createElement('li');
                 child.className =  "resultlistitem";
                 child.innerHTML = '<a href="' + result.Url +'"><img src="' + result.Thumbnail.Url +'" alt="' + result.Title +'" /></a>';
                 parent.appendChild(child);
             }
        }
       
         var AppId = "&Appid=<YOUR APPID HERE!>";
         var serviceURI = "http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=searchDone&sources=image";

    </script>
</head>
<body>
 Type in a search:<input type="text" id="searchText" value="sushi"/>
        <input type="button" value="Search!" id="searchButton" onclick="search()" />
               <ul ID="resultList">
                    
                </ul> 
</body>
</html>