Pimping JSON - YQL now offers JSONP-X!

Written by on July 9th, 2009 in Uncategorized.

Yesterday’s announcement of Yahoo’s YQL now supporting insert, update and delete overshadowed another interesting new feature: JSONP-X output.

Here’s what it is and why it is useful: YQL data can be returned in XML which is annoying to use in JavaScript (for starters because of crossdomain issues in Ajax). JSON is much easier as it is native to JavaScript. JSON-P makes it even more easy for us to use as JSON data wrapped in a function call allows us to get the data by creating script nodes dynamically.

Where it falls apart is when you want to get back HTML from some system (not on your own server) and use it in JavaScript. You either need to convert the XML to JavaScript and create HTML elements from it or you need to loop through a JSON construct and assemble HTML from it. JSONP-X works around that step for you. In essence it is XML as a string returned inside a JSON object.

XML:

XML:

  1. <results>
  2.   <div id=“following”>
  3.     <span>
  4.       <a href=“http://twitter.com/codepo8″>Codepo8</a>
  5.     </span>
  6.   </div>
  7. </results>

JSON:

JAVASCRIPT:

  1. {“results”:[
  2.   “div”:{
  3.     “id”:“following”,
  4.    “span”:{
  5.      “a”:{
  6.        “href”:“http://twitter.com/codepo8″,
  7.        “text”:“Codepo8″
  8.      }
  9.    }
  10.  }
  11. ]}

JSON-P:

JAVASCRIPT:

  1. foo({“results”:[
  2.   “div”:{
  3.     “id”:“following”,
  4.    “span”:{
  5.      “a”:{
  6.        “href”:“http://twitter.com/codepo8″,
  7.        “text”:“Codepo8″
  8.      }
  9.    }
  10.  }
  11. ]})

JSONP-X:

JAVASCRIPT:

  1. foo({“results”:[
  2. “<div id=\”following\”><span><a href=\”http://twitter.com/codepo8\”>Codepo8</a></span></div>”
  3. ]})

The way to invoke the JSONP-X output is to provide a format parameter of xml and a callback parameter.

This allows me for example to get the list of people I follow on twitter from my twitter homepage and display it in another document with a few lines of JavaScript without any need of using the API or having a local proxy:

HTML:

  1. <script type=“text/javascript” charset=“utf-8″>
  2. function foo(o){
  3.   var out = document.getElementById(’container’);
  4.   var content = o.results[0]
  5.   out.innerHTML = content.replace(/href="\//g,’href="http://twitter.com/’);
  6. }
  7. </script>   
  8. <script type=“text/javascript” src=“http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Ftwitter.com%2Fcodepo8%22%20and%20xpath%20%3D%20%22%2F%2Fdiv[%40id%3D%27following_list%27]%22&format=xml&callback=foo”>
  9. </script>

More details on this are available in this blog post.

Source: Ajaxian » Front Page
Original Article: http://feedproxy.google.com/~r/ajaxian/~3/eZQ81FctNew/pimping-json-yql-now-offers-jsonp-x

Comments are closed.



Site Navigation