Blog

Tutorial: Amazon.com Search API

Posted on
Combining JSON and XSLT

Combining JSON and XSLT Figure 6 Combining JSON and XSLTBy using Amazon’s XSLT service to transform its own XML output into JSON objects, it is very easy to dynamically include this data in a web page. As illustrated in the above diagram, you do this by using the Document Object Model to create and append a new SCRIPT element to the document, which will be evaluated as it loads onto the page. The script element is appended and/or destroyed at page load using the JSON Scriptbuilder function in the following code:

// JSON ScriptBuilder Function and Prototype, from Jason Levitt of Yahoo!
// code found here: http://devx.com/webdev/Article/30860/1954
    function JSONscriptRequest(fullUrl) {
      this.fullUrl = fullUrl;
      this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
      this.headLoc = document.getElementsByTagName("head").item(0);
      this.scriptId = 'azScriptId' + JSONscriptRequest.scriptCounter++;
    }
    JSONscriptRequest.scriptCounter = 1;
    JSONscriptRequest.prototype.buildScriptTag = function () {
      this.scriptObj = document.createElement("script");
      this.scriptObj.setAttribute("type", "text/javascript");
      this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
      restquery = this.fullUrl + this.noCacheIE;
      this.scriptObj.setAttribute("id", this.scriptId);
    }
    JSONscriptRequest.prototype.removeScriptTag = function () {
      this.headLoc.removeChild(this.scriptObj);
    }
    JSONscriptRequest.prototype.addScriptTag = function () {
      this.headLoc.appendChild(this.scriptObj);
    }

Take note of the ‘fullUrl’ argument for the JSONScriptRequest function as this is the most important line of code in the application: the request string to the web service. It includes the url address of the XSLT stylesheet we will use to format and transform Amazon’s XML output into JSON.