Thursday, May 19, 2011

Display JSON results

JSON (JavaScript Object Notation) is a great straight forward way to transfer information from one application/server to another. It's string-based, array-oriented, and does not carry with it the redundancy of XML or (shudder) SOAP. And the best feature in a web application: it's immediately transferable to a JavaScript object, without the need for (an explicit) parsing.

Add to the mix jQuery - a JavaScript framework that makes using JavaScript and writing dynamic web pages a snap. Once I picked it up, I couldn't go back. jQuery is now embraced by many - including Microsoft and Google, who include it in their default web templates, and provide hosted CDN versions of its latest versions.

jQuery shines when it comes to AJAX transactions - you can get a JSON result from a web service using one instruction! Going over the reply is also a snatch. I found myself many times just needing to dump the results on the page - either for debugging purposes, or so I could copy/paste them somewhere.

Here is a short code snippet that I use to get a JSON result from a local web service (a remote request requires JSONP - future post), and dumps the results in a form of a list. It assumes a single-level array reply and that you have a <DIV> element on the page called "result":


  1. Line 1 includes version 1.5.2 of jQuery from the Microsoft CDN
  2. Line 4 will make sure the function will run when the document has been fully loaded and drawn
  3. Line 5 calls the JSON service and sends the results to a function
  4. Line 8 iterates over the result object and creates an array of <LI> elements
  5. Line 14 creates a new <UL> element, applies a CSS style to it, attaches the <LI> elements and places it inside the result <DIV>
That simple!

1 comment:

  1. json is a very interesting language to be used. very good tutorial and can hopefully help me in building json in the application that I created for this lecture. thank you


I enjoy all comments - unless they're spam. If you want to push a product/service/site - this is not the forum.