JSON For Your MultiValue Web Site

JSON is an exciting technology, not because of what it is, but simply because of what can be achieved using it. JSON is an acronym for JavaScript Object Notation, which neatly encapsulates what it is all about — a serialization format for JavaScript objects. That may not sound too exciting in itself, until you discover how it can enhance your MultiValue backed web applications.

What is JSON?

JSON is characteristically mentioned in the same breath as XML. Both are standardized formats for encoding and representing complex information. Both are syntactically simple and highly legible. Both are easy to parse and to generate. And both are valuable not in themselves, but only in as far as they support rich and powerful toolsets. XML is, after all, nothing more than text organized into a set of nested elements according to simple rules. Its usefulness is in the degree to which it has been adopted by tools as diverse as the Microsoft Office document formats and web services and the existence of layered technologies for transforming and validating content. The same can be said of JSON.

JSON is a serialization format for representing objects. Just like XML, this means that it must support nested hierarchies and that the encoding is based on holding values for the various elements or attributes of an object. In the case of XML, this is done through tags, but nothing clearly defines when one should use an element and where one should use an attribute. In the case of JSON the format is even simpler: JSON serializes to a simple series of key and value pairings:

{accountCode='A123',surname='smith', forename='jane'}

Using JSON

So far, nothing to write home about. What matters here is not the medium, but the message. On the server side, JSON is extremely simple to parse and to generate from MultiValue Basic. On the client side, JSON libraries exist (and there are plenty of these) to convert this notation directly into dynamic JavaScript objects, enabling developers to write compact object representations in their code and, more important, to pass around these objects ready to be used in their web pages.

As an example, take a look at the free Dojo Toolkit (www.dojotoolkit.org, also hosted on Google). This is one of a number of free libraries offering methods for performing asynchronous http calls where the results are expected in JSON format. Here the dojo.xhrPost method is used to call an mvScript page that will return UniVerse data in JSON format and specifying the outline of two functions to call, one on success and one on failure (fig. 1).

function fetchRequest(id){
   {url : "http://localhost/tasks2/ttReqJSON.wsp",
    content: {
       "id" : id
    handleAs: "json",
          load: function(data, args){
            request = data;
    error: function(error, args){

Fig. 1 - A JSON call through the free DoJo Toolkit.

This example contains two pieces of good news: first, by using JSON you can generate JavaScript objects from server code ready to be consumed by your web pages; and second, the toolkit makes the call using Ajax, avoiding the full page refresh that bedevilled early web site development. Ajax, like all HTTP calls, can return data in any format and so long as your middleware does not automatically turn your content into HTML or an equivalent, then it is easy enough to present your data according to JSON syntax rules. Once the results have been automatically parsed to create your JavaScript object(s), the first advantage of JSON is the ease with which the elements of such an object can be addressed (fig. 2).

// update the content of the form with the request data
function loadRequest(request){
if(request.message != ''){
 } else {
   dojo.byId("idField").value = request.id;
   dojo.byId("summaryField").value = request.summary;
   dojo.byId("statusField").value = request.state;
   dojo.byId("categoryField").value = request.category;

Fig. 2 - Accessing the object properties.

JSON Encoding

The rules for encoding JSON are simple. Elements are represented as a series of comma delimited key and value pairs, with the value being enclosed in quotation marks (even for numeric values). To permit the full range of content, JSON uses a small handful of escape sequences that are similar to those used in C-based languages for encoding delimiters and special values that may appear within the text (fig. 3)

\ \\
' \'
/ \/
Line Feed(Char 10) \n
Carriage Return(Char 13) \r
Form Feed(Char 12) \f
Tab(Char 9) \t
Hexadecimal Character \xNN?

Fig. 3

What happens when you want to encode more complex data, such as MultiValued fields or listings? JavaScript objects permit any member to be an array, including arrays of other objects, and thus JSON permits nested content, again using a simple format (fig. 4).

{ identifier: 'name',  label: 'short',  items: [ 
  { name:'t6007', taskId:'6007', type:'task', short:'Spectrum article on report mining.', 
    category:'ARTICLES', status:'OPEN' },
  { name:'t6101', taskId:'6101', type:'task', short:'Spectrum article series on OpenXML', 
    category:'ARTICLES', status:'CLOSED' },
  { name:'t6102', taskId:'6102', type:'task', short:'Spectrum article on REFORMAT', 
   category:'ARTICLES', status:'CLOSED'} ...]

Fig. 4 - JSON encoding nested data

Many standard libraries of visual JavaScript components — including the grids, tree views and complex controls that are provided alongside the DoJo toolkit — can be bound directly to this content (fig. 5)

spectrum - JSON 1

Fig. 5 - Binding components to JSON objects.

Passing Dynamic Functionality

Thus far, this could have been achieved using XML to represent the data, though with the added workload of parsing the XML document content. Where JSON adds further value is by passing objects, not data — objects that expose dynamic functionality.

Just as in other languages, JavaScript objects contain both properties and methods, and so these methods can likewise be serialized into JSON:

{status:'error', validation:function(){alert("Im sorry Dave…");}} 

This leads to some interesting scenarios. You can return objects complete with their own custom methods for validation and formatting, for deriving content, or controlling the flow of an application. You can wrap code into dynamic objects as a means of hiding it from browsers (dynamic objects are not visible through a simple source view), or to expose limited functionality that is filtered based on user preferences or security requirements.

By thinking outside the box and generating these directly from the server either through Basic code or using template libraries, you can add another level of complexity and vibrancy to your web applications.


View more articles