JSON for Dummies (like me) Part 1?

JavaScript Object Notation (JSON) is making the rounds on the RSS feeds and I finally got some time to sit down and figure out what it is all about. There is certainly no lack of an official definition for what JSON “is”, but I thought I would take a stab at writing down how I thought I could use it, and then go from there.


I am just winding down a project where I designed a web content management system with .NET 2.0, that relies heavily on AJAX, DHTML, and Javascript, and I realized that the way I have been returning responses to the client is similiar to JSON, and it would not take me much to adapt these responses to the JSON notation.

In a nutshell, if a user is in the middle of creating a piece of web content and wants to save the content, I send the content to the server with an AJAX post, perform any validation on the server, and then return a response of success or failure, which in turn, performs an action (like hiding an AJAX activity icon or displaying a “content saved” message), or displays an error message.

What I had been doing was returning an XML stream that had an integer node to signify success or failure, then another node with any applicable error messages. It was the function called upon completion of the ajax request that would change the display of an acitivity icon, prompt the user with an error, or in some cases refresh the page.

For example, an unsuccessful response might look like this :

<return>
     <result>0</result>
     <message />
          The description and category fields are required.
     </message>
</return>

To process this return stream would require something like this (I am using protoype, of course) :

function ajaxOnComplete(originalRequest){
     var domXML = originalRequest.responseXML;
     var xmlDoc = domXML.documentElement;
     var returnResult = xmlDoc.getElementsByTagName("result")[0].value;
     var returnMessage = xmlDoc.getElementsByTagName("message")[0].value;
     if(returnResult == '1'){
          $(ajaxActivityIconId).style.display='none';
          $(statusDisplayDiv).innerHTML ='content saved'
     }else{
          alert(returnMessage);
     }
}

Pretty simple right? Problem is, since the page updates that I want to take vary depending upon what action the user is undertaking, I end up with a dozen or more functions to handle different AJAX responses. But what if I changed that unsuccessful AJAX request to return a JSON notation like this:

{"ajaxReturn": 
     {
          "actionToTake": 
               "alert('The description and category fields are required.')"
     }
}

The successful return would look like this:

{"ajaxReturn": 
     {
          "actionToTake": 
               "$('ajaxActivityIconId').style.display='none';$('statusDisplayDiv').innerHTML ='content saved'"
     }
}

Then I could use a single generic function to handle all the AJAX responses since all I would be doing is performing an EVAL function. Something like:

function processJsonResponse(originalRequest){
     var domText = originalRequest.responseText;
     // first eval creates the javascript object
     var jsonResult = eval("(" + domText + ")");
     // second eval actually performs the function required to finish the AJAX transaction
     eval( jsonResult.ajaxReturn.actionToTake );
     // still researching why I need the extra parenthesis in the first eval and not the second
}

Not only is that alot less code to process the response, but I would be able to process multiple AJAX responses with a single function instead of customized functions for each response.

It does not get more basic than that. Next post I’ll try some more complex stuff like arrays, which is where the meat of the JSON vs XML fight kicks in.

Part two

4 Responses to “JSON for Dummies (like me) Part 1?”

  1. Jake Howlett Says:

    “still researching why I need the extra parenthesis in the first eval and not the second”

    Confusing isn’t it. I have no idea why those brackets are needed at all.
    One observation: I think you could simplify things like this:

    {ajaxReturn:
    {
    actionToTake:
    function(){alert(’The description and category fields are required.’)}
    }
    }

    Then after your first eval() you could skip the second and simply call:

    var jsonResult = eval(”(” + domText + “)”);
    jsonResult.ajaxReturn.actionToTake;

    I THINK.

  2. Administrator Says:

    I did say this was for dummies, right?

    Thanks for the reminder about object functions, that will definitely be in part two.

  3. My Portal Project » Blog Archive » JSON for Dummies part 2 Says:

    […] My Portal Project Nowadays it’s all about portals; portals and ball bearings « JSON for Dummies (like me) Part 1? […]

  4. My Portal Project » Blog Archive » JSON for Dummies part 3 - Faster than XML? maybe not Says:

    […] So parts one and two covered the basics of using JSON, what about this JSON/XML battle? In this post we’ll take a peak at how JSON can be used as a replacement for XML in some cases, and even pit the two side by side in a performance test. […]