marco rosella

Interactive Designer & Developer.




The X from JSON – second part

jlogo.jpgThis is the second part of a series of three posts dedicated to
JSON, a javascript for the description and the transport of data.
In the first part we saw the comparison between its sintax and the one of XML, the ‘chairman’ in the same category; today we’ll speak about some differents between the two formats stopping in particular
on their rule in the client-server interaction. (with some downloadable samples)

JSON vs. XML

JSON could have the right peculiarity to get the better of XML? To find some answer, I had a look at the ‘official comparison’ on the JSON site, at a indirect parallel by Peter-Paul Koch, at ‘JSON message’ on AjaxPatterns and
at some memo taken by myself in a post-it when I revise last post.
Let’s take as start point this sentence:

It (JSON) is easy for humans to read and write.

We are so sure of this? Is that true in the same way for the ‘Persons’ – the developers that will create, read or modify the data – and for the ‘Software’, the server-side application that will generate or parse the same data?
Code creationPersons: There are on the ring two opposite way to write the code: a markup language (like XML) fight with a scripting language (like Javascript).
To open and to close the tags following the right hierarchy is probably quicker than respect the opening and the closing of several curly braces, square brakets, round brackets.
However, a JSON appear thiner under two aspects:

~ The redundancy on the name description, in other words the containing of the data between tags.

    <color>yellow</color>

is substituted by some simple name/value pairs:

   "color": "yellow"

~ Two or more elements with the same name:

    <color>magenta</color>
    <color>purple</color>
    <color>greenish</color>

could be compacted in an array:

    "colors": ["magenta","purple","greenish"]

Extending this rules to the several objects and name/value pairs inside them, the JSON sintax will result without doubts lighter than XML one. Under my point of view, Secondo il mio punto di vista, however:

~ After the third nesting level – the root element have inside at least a ‘grandchild’ element – recompose the object hierarchy became very complicated. (see for example the first parallel in this ).

~ As already said last time, JSON hasn’t a DTD or a schema that control the document structure as happens with the XML. Doesn’t exist rules, so, to handle for example attributes and ‘mixed content’ elements, in other words those that have in the same time text child and element child.
The attribute handle happen represent them as the first child of an element, avoiding in this way the ‘metadata role’ related to that particul element.
About ‘mixed content’, instead, some weeks ago D. Crockford
suggested
in reply to my doubts to create a child called “content” and to link to it the value of the text inserted within that element. Another example has done by ‘”JSON-like SPARQL Query Results serialization in
SPARQL, a query language for RDF (the standard for the description of metadata represented as graphs) where the text content of an element is identified by the name “value”.

Software: A common server-side language help to automatize – simplifying it – the developer work, so the differences are the same above.

Code readingPersons: A code must be readable for ‘humans’ above all to walk towards the developer himself that will attend to a possible debugging. About XML it’s easy for sure to undestand the document hierarchy, and in this are useful the Mozillas and Explorer that display an automatic indentation of the files.
(you can try it with any RSS feed)
With JSON, instead, the debugging became hard: sometimes javascript could be generated in a comprehensible way, like for example in the JSON translation of RSS feed by John Resig ,
sometimes could be displayed in only a line like in the Yahoo APIs.

Software: Have you ever heard about Rich Internet Applications? Until few times ago I was sure that it was related to the new economy in the speculative bubble time,
or with this fellow that fellow that come in to sell pixels at the gold weight. Mannaggia, nothing of that: it’s about a way to conceive web applications moving a part of the server’s work load server to the client-side with the goal to speed the global performances. One of this task could
analize and reutilize, through a browser, the informations coming from the server using some client-side languages like, first of all, Javascript.
With XML this could be done in two ways:
1) Using ‘parsing’ of the XML, that is to say prepare a data structure
modifiable by the Document Object Model (DOM). Obtained the various values it could be possible to create dinamically the HTML elements.
2) Using XSLT,
a markup language (it’s XML) that transform an XML document in other formats (like other XMLs, HTML or SVG) selecting the nodes through a language called XML Path (XPath). The parsing and the control of transformations
is played in Mozillas by the XSLT Processor, while in Explorer by a dedicated ActiveX (MSXML2-3); two js library that allow to call both are
Sarissa and more recent
Freja (It’s also available a GoogleCode project called AJAXSLT that even emulate in javascript
the two processors, by has been put in stand-by by the author himself that
suggest in the meantime the two framework cited above.
).

Using JSON, instead, all become easier. Parsing is played by only a function called eval(): this allow to execute every string passed as parametere
in the same way of an ordinary javascript code. In this case it will transform a JSON message in a Javascript object easy to use by the DOM.
The eval() function, however, doesn’t enjoy a good reputation cause by reason of its potential dangerousness: there is no guaranty that the string doesn’t contain some functions that, execute by our browser, could cause damages. For this reason Crockford released a library that allow to do the JSON parsing without using eval() function and to convert, viceversa, a Javascript object in a JSON text.

If I can deduct a first personal opinion from the paragraphs above:
1) JSON never catch up XML in the containment and the description of data.
The extensibility (the “X” from JSON) exists under a certain level, and I see very difficult to entrust to a so complicated format the management of very big amount of data. The first sample that came in my mind is a ‘english dictionary’ (the same that I don’t know, as you can read here :-) ) composed by thousand of elements, related everyone to metadata that complete the meaning and containg links to many other elements.
A structure like this could be hypothetically described by a RDF graph, that had as ‘official sintax’ is just XML.
2) JSON appeare instead a good alternative to XML in the exchange of data.
Or better, in the exchange of the small data that for example could come from query results. To this point, let’s see right away some ‘asynchronous’ example.

AJAX or AJAJ?

In the previous section I speak about “fast iteration between client and server”:
the principal artificier of this result, as everybody know, is named XMLHttpRequest and its use take flight thanks to a succesful operation of technologic branding. The javascript in question allow to send HTTP requests to a server without wait for a reply related to a previous sending, as happens in the ordinary communication flux.
Approximately the exchange of informations work in this way:

  1. creation of the XMLHttpRequest object
  2. opening of a connection through a open function with parameters the HTTP method (get,post, put…), the URL of the requested resourceta and a boolean variable related to the asynchronism
  3. calling of a function at the receipt of the server reply
  4. sending of the body of the request

These items could be translated in (GET method) in this code:

var xmlhttp = (window.XMLHttpRequest)? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://musicsite.buz/song.php?id=332", true);
xmlhttp.onreadystatechange = handle;
xmlhttp.send(null);

function handle() {
   if (xmlhttp.readyState == 4) {
    if (http.responseText.indexOf('invalid') == -1) {
       var resp  = xmlhttp.responseXML;
       //and a series of operations....  
   }
}

I will omit intentionally some particularities (waiting time, handling of header, cross-browser assigning, other HTTP methods etc.) to shine the light to
what that mainly interest us, that is to say the reply that come from the server. This could be identified by two different parameters:
responseXML, that contains the DOM tree obtained from the parsing of the XML file played by the XMLHttpRequest; responseText, that represent instead a parameter related to a string type reply and could be used – as in this case – to test a possible presence of error in the receipt.

Let’s suppose that the server, through this simple PHP script, place at our disposal a series of data (a couple of informations about a song) in two formats: XML and JSON .
We want to print this informations in our HTML page inserting them in a list like this:

  <dl class="song">
    <dt>song title</dt>
    <dd>Performed by: Group name </dd>
    <dd>Published in: year</dd>
  </dl>

Let’s try to do it using the three methods seen in the previous section XML+DOM, XML+XSLT, JSON+DOM.
With the first and the third method trought the DOM will be created some new HTML nodes within will be inserted the informations taken from the resource. With the second method, instead, the same HTML elements will be created directly with the XSLT.

XML+DOM – Let’s request to the server the data in XML format:

<song>
   <title>Birdman</title>
   <group>McDonald and Giles</group>
   <year>1971</year>
 </song>

The handle function, that we’ll use to manipulate the DOM object obtained thanks to the XMLHttpRequest, will be the following:

function handle() {
   if (xmlhttp.readyState == 4) {
    if (xmlhttp.responseText.indexOf('invalid') == -1) {
      var resp = xmlhttp.responseXML;
      var dlist = document.createElement('dl');
      dlist.className = 'song';
      var title = document.createElement('dt');                  
  title.appendChild(document.createTextNode(resp.getElementsByTagName('title')[0].firstChild.nodeValue));
     dlist.appendChild(title);
     var group = document.createElement('dd');
     group.appendChild(document.createTextNode('Performed by: ' + resp.getElementsByTagName('group')[0].firstChild.nodeValue));
     dlist.appendChild(group);
     var year = document.createElement('dd');
     year.appendChild(document.createTextNode('Published in: ' + resp.getElementsByTagName('year')[0].firstChild.nodeValue));
     dlist.appendChild(year);
     document.getElementById('content').appendChild(dlist);
	}
}

To have acces to one of the values (ad esempio, title) it’s not so direct: it must select the tre root, responseXML; it must search within it the first tag called ‘title’; it must to select the first child node and take his value. The verbosity could increase if in the document there was, for example, a tag called ‘album’ that contain inside another tag called ‘year’. To have the access to the value inside our ‘year’ belong ‘song’ must be to specify the path in this way:

xmlhttp.responseXML.getElementsByTagName('song')[0].getElementsByTagName('year')[0].firstChild.nodeValue. 

Argh!

XML+XSLT – At the beginning we’ll need an XSLT stylesheet (that I’ve called in a flash of originality stylesheet.xsl) that transform the XML in HTML.
The file contains inside this code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">
 <dl class="song">
    <dt><xsl:value-of select="//title"/></dt>
    <dd>Performed by: <xsl:value-of select="//group"/></dd>
    <dd>Published in: <xsl:value-of select="//year"/></dd>
  </dl>  
</xsl:template>
</xsl:stylesheet>

In this case the node selection through XPath has been immediate.
If we want to make a client-side transformation using the Freja framework, the handle is not necessary any more. Freja think about to initialize the XMLHttpRequest e call the XSTL processors: it will mustto indicate the XML source, the XSLT and the element of the HTML page where we want to append the result.

var source  = new Model('../resource.php?type=xml');
var stylesheet = new View('xslt/stylesheet.xsl');
Controller.onLoadComplete = create;
Controller.loadAssets();

function create() {
  Controller.render(source, stylesheet, { placeholder: 'content' });
}

The performances of the XSLT stylesheet grow at the increase of the hierarchical levels to manage, so for me they are the ideal solution (with XQuery, but it’s better not to digress) for the handling of XML data. For smaller groups of data like our case, though, it could be suggested the creation of the HTML nodes through the function seen in the last method.

JSON+DOM – Let’s request now to the server in JSON format:

{ "song": { 
  "title" : "Birdman",
  "group" : "McDonald and Giles",
  "year" : 1971 
  } 

The creation of the XMLHttpRequest and the handle function are necessary again:

function handle() {
   if (xmlhttp.readyState == 4) {
    if (xmlhttp.responseText.indexOf('invalid') == -1) {
     var resp = eval('(' + xmlhttp.responseText + ')');
     var dlist = document.createElement('dl');
     dlist.className = 'song';
     var title = document.createElement('dt');                  
     title.appendChild(document.createTextNode(resp.song.title));
     dlist.appendChild(title);
     var group = document.createElement('dd');
     group.appendChild(document.createTextNode('Performed by: ' + resp.song.group));
     dlist.appendChild(group);
     var year = document.createElement('dd');
     year.appendChild(document.createTextNode('Published in: ' + resp.song.year));
     dlist.appendChild(year);
     document.getElementById('content').appendChild(dlist);
    }
}

As said above, the eval() function do the parsing of the JSON string return a javascript object. To have the access to the element inside the object will be quicker than to analyse the DOM tree deduced from the XML. If we’ll make again the example hypotetical tag ‘year’ inside another section of the source code, the value of the ‘year’ inside ‘song’ could be obtainable in this way:

eval('(' + xmlhttp.responseText + ')').song.year

so in the handle.

Other options – 1) We can to use for both formats, instead of DOM W3C, the not-standard but very effective innerHTML : xmlinnerhtml.js & jsoninnerhtml.js.
2) We can to request to the server directly the data formatted in HTML, having the possibility to insert them in a flash in pur page. But this case, by the way, goes off topic.

The three examples are naturally available for the download .

A lexical conclusion: everybody knows that AJAX is the acronym of “Asynchronous Javascript and XML”. Replacing the ‘XML’ word with ‘JSON’ the acronym could become AJAJ, “Asynchronous Javascript and Javascript” – but in this case we saw that will remain in the game another ‘XML’, the one from XMLHttpRequest.
We have seen also that eval can do the parsing of JSON and make in this way the XMLHttpRequest almost superfluous…
This one, combined with On Demand Javascript, feeds and JSON APIs, will be the subject of the next part. A presto!