RSS feed
<< September 10, 2008 | Home | September 12, 2008 >>

JSON Prettifier with JPublish DWR; simple

I am working a lot with AJAX these days for a project where JSON is used almost everywhere. And as you know, reading too much JSON, especially JSON containing complex data, is not an attractive job ;)

There are a lot of tools you could use but most of the ones I know are Javascript based and available on public web servers, and most probably that you don't want to send sensitive data over the wire?! This is why I tried to see how hard would be to implement my own version of a simple JSON Prettifier? 20 minutes later and I have my own simple tool :)

Tools? json-lib, JPublish and the JPublishDWR module for creating a simple but useful AJAXified UI.

Check below how easy it is.

First of all, let's write a simple beanshell action to convert a JSON string to a JSON object and from there to a prettified String. Why converting it to JSON? Well, first of all because you may want to validate it and also throw some exceptions and help the debugging process. Anyway, for simplicity I am not showing the validation code.

So, here is the Action (JSONPrettyPrint.bsh):

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

/**
* simple Action used to prettify a JSON string received from an AJAX call or
* from any JPublish Page context.
* Using: http://json-lib.sourceforge.net/ for JSON parsing and formatting
*
* @author <a href="mailto:florin.patrascu@gmail.com">Florin T.PATRASCU</a>
* @created 2008-09-11
*/

jsonString = context.get( "jsonString");
prettyJson = "";

if( jsonString != null && jsonString.trim().length() > 0){
   try{
       jsonFromString = JSONObject.fromObject( jsonString);
       prettyJson = jsonFromString.toString( 2, 1);
   }catch (e){
       // implement your own validation code here
       prettyJson = "JSON parsing/formatting errors: "+ e.getMessage();
   }

}else{
   prettyJson = "prettify ... nothing?";
}

context.put( "prettyJson", prettyJson);


Now let's declare it in WEB-INF/dwr.xml:
    ...
    <create creator="jpublish" javascript="JSONPrettyPrint" scope="application">
        <param name="class" value="ca.flop.jpublish.dwr.DWRJPublishActionManager"/>
        <param name="actionName" value="JSONPrettyPrint.bsh"/>
    </create>
    ...
  </allow>

And then add the following js/html snippet to your web page where you want to paste JSON strings and prettify them:
...
<script type='text/javascript' src='$request.ContextPath/dwr/interface/JSONPrettyPrint.js'/>
...
<table>
    <tr>
      <td valign = "top">
        <div id="output" style="display:block;">
            <small>
                <textarea rows="2" cols="20" id="json_string">{ "firstName":"John", "lastName":"Smith", "address":{ "streetAddress":"212ndStreet", "city":"NewYork", "state":"NY", "postalCode":10021 }, "phoneNumbers":[ "212555-1234", "646555-4567" ] }</textarea>
                
            <small><pre wrap id="response"></pre></small>
        </div>
      </td>
    </tr>
      <tr>
          <td colspan="2" align="center"><input id="submit" type="submit" value="prettify?" onclick='
              var params = {};
              params["jsonString"] = DWRUtil.getValue( "json_string");
              JSONPrettyPrint.execute( params, function( response){
                  dwr.util.setValue( "response", response.prettyJson);
              });'/>
          </td>
      </tr>    
    
</table>
.....


Well that's all it takes to build a JSON prettifier with JPublish and DWR. Also don't forget to add the json-lib and supporting libraries to your WEB-InF/lib folder!

However if you're not interested to use the implementation above but still looking for a similar tool, then I recommend using this one: http://curiousconcept.com/jsonformatter/

Have fun!
-florin

PS
Make sure the json-lib supporting libraries are in the WEB-INF/lib, they are:
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
http://commons.apache.org/beanutils/
Tags :