Monday, June 09, 2008

My first JSON Implementation

I wanted to share my first real use of JSON (JavaScript Object Notation) I created today at work.  The reason I find this exciting is cause I never really understood the use of JSON or how to create and use it.  I found a simple use when I wrote about pulling in twitter updated into my blog using jQuery and the Twitter API using the JSON data, but I didn't create the JSON and was just consumming it.

Well today I was tasked with creating a JavaScript array that could be easily updated by an administrator of a web site and the data would be used to populate a dropdown box.  Yes there are probably better solutions to populate a dropdown box but this was what I was tasked with. 

Now a year ago, I would have probably created an XML file to hold onto this data but a recent blog post from Jeff Atwood over at Coding Horror made me realize that XML is ugly.  From that article JSON seemed like a cleaner choice.

So basically my data needed to hold geographical regions of the US with sections or cities for each region.  Each region/city would have a url associated with it.  So in a separate js file I created this:

{ regions: [
                    {
                        text: "NorthEast",
                        value: "http://www.damnralph.com/northeast",
                        sections: [
                                         {
                                            text: "New York",
                                            value: "http://www.damnralph.com/newyork"
                                         },
                                        {
                                            text: "Boston",
                                            value: "http://www.damnralph.com/boston"
                                         }
                                     ]
                   },
                    {
                        text: "South East",
                        value: "http://www.damnralph.com/southeast",
                        sections: [
                                        {
                                            text: "Orlando",
                                            value: "http://www.damnralph.com/southeast"
                                        }
                                      ]
                    }

                ]

}

So looking at this you can see that it's very clean and easy to read.  We can see that it's two levels deep and we can see which sections are related to which regions at a quick glance.

Now I needed to take this JSON data and consume it and populate a dropdown.  I turn to jQuery to help me out (which was very slow today due to the 1.5 release of the UI plugin).  Here is the code to consume display it:

$(document).ready(function(){
    $.getJSON("sections.js",function(json){
        $.each(json.regions, function(i,ritem){
            $("#select_dropdown").append("<option value=" + ritem.value + ">" + ritem.text + "</option>");
            $.each(ritem.sections, function(i,sitem){
                $("#select_dropdown").append("<option value=" + sitem.value + ">--" + sitem.text + "</option>");
            });
        });
    });
});

This requires a select element on the page with an id of select_dropdown. 

Download the example code JSON_Example-DamnRalph.zip (1.24 KB)

Update: So an interesting problem came up at work today where we needed to validate the JSON because the data we entered had a syntax error (we figure this was the case cause it wasn't working as expected) and so we needed a validator to validate the JSON data.  Unfortunately the way we are consumming the JSON if it tries to parse it and it's not valid then the user doesn't get an error (is this the desired choice in jQuery's getJSON method?) so there is no feedback to what the sytax problem might be.  We found this online JSON Validator that worked to help us identify the syntax errors.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):

Blog Posts by:

Currently Viewable:

My Twitter Updates

View Twitter Page