This workshop is for you, if:

  • You are looking for a data structure to store your data for easy javascript access
  • You have seen JSON structure but do not know, how to access it using javascript

This workshop is not for you, if:

  • You have no idea about client side scripting

This workshop intends to provide hands on example on creating JSON structure and accessing the contents of the JSON using Javascript.

'JSON' the new kid in town

JSON which stands for JavaScript Object Notation is the new buzz word and will definitely look good in your resume! But, how is JSON useful from a technology perspective.

  • JSON can store data in the client side, where data security is not important.
  • JSON can be used for data exchange just like XML. But, why not XML itself? JSON comes handy when the exchanged data needs to be handled in the client side. JSON structure is easy to be manipulated in client side using javascript.

Workshop Requirement

Let us say, we need to maintain the summary of contents of this website. We want the data not to be maintained in database. We need to get information from a data structure using Javascript and of course, this data is not sensitive. The website contains, two sections (while writing this article), Java Programming and Stock Market. Each section contains categories and each category contains articles. Based on this data, we would like to see the number of pages in Java category etc.

Meeting JSON flesh and blood

Enough talking about JSON! Let us actually see a JSON structure. The code snippet provided below shows a JSON structure assigned to a Javascript variable. When we use JSON for data exchange, we will write or receive JSON structure starting from braces without the javascript variable. To convert this into a javascript variable, we can use 'eval' function, which is not recommended. There are parsers available in JSON.org which converts the JSON structure to javascript variable.

var varSiteData = {
  "sections" : [ //Array
     {//Each element in array, ie. Section is a structure not a simple attribute
      "name": "Java Programming", //this is a simple attribute
      "categories": [
      {
         "name":"Java Basics",
         "articles": [
         {
            "name" : "Java Hello World",
            "pages" : "1",
            "author" : "Tech Programmer"         
         },
         {
            "name" : "Java Hello World using Eclipse IDE",
            "pages" : "5",
            "author" : "Tech Programmer"         
         },
         ...
         ...
       ]
      },
      ...
      ...
     ]
    },
    ...
    ....
   ]
 }
 

Let us try to understand the syntax. JSON always start and end with curly braces. They contain attributes. The value of each attribute can be simple string, a structure (which internally is composed of many simple string attributes), array of simple string or array of structures. Here "section" is an attribute. How many sections we have in the site? Two, Java programming and Stock market. This calls for an array. Arrays are defined by square brackets. Now, each section contains categories. Also, each section needs a name to be stored. So, we have added an attribute by "name". Attribute "name" is a simple string. Other attributes shown work in the same way. Click here to download the complete JSON structure stored in JS file.

  • An attribute name or key cannot start with numeric value. Although this is not a rule written anywhere, when the key or attribute name starts with or is a numeric value, the javascript which parse through the JSON does not understand the key. A simple workaround to resolve this issue is to append a constant string before the numeric value. Example: "str_25"

 One more important thing is, if for an attribute, the value needs to be multiple attributes but not an array, then it is achieved using curly brackets only. A simple snippet which shows the attribute structure for Alphonsa mango:

"alphonsa" : {
  "type": "mango",
  "taste": "sweet",
  "color": "yellow"
}

Well, that's that. We got started with JSON. But, let us try to have a quick look, why JSON is compared with XML. See the above JSON structure in an XML format.

<?xml version="1.0" encoding="ISO-8859-1"?>
<sections>
  <section>
     <name>Java Programming</name>
     <category>
        <name>Java Basics</name>
        <article>
           <name>Java Hello World</name>
           <pages>1</pages>
           <author>Tech Programmer</author>
        </article>
        <article>
           <name>Java Hello World using Eclipse IDE</name>
           <pages>5</pages>
           <author>Tech Programmer</author>
        </article>
       ...
       ...
     </category>
  </section>
..
</sections>

Validating JSON structure

Just like we validate XML structures using Internet Explorer and other tools for well-formedness, there are certain JSON viewers available, which verify the JSON structure and provide details regarding any missing braces etc. JSON Viewer is one such hand helpful too.

Javascript and JSON

Now, let us see how Javascript can access different elements within the JSON structure. We will try to calculate the total number of pages in 'Stock Market' and 'Java Programming' section. The HTML page includes the JSON data from a JS file. The javascript present in the HTML page iterates through the JSON structure to determine the result.

See the below javascript function, with comments explaining how the JSON structure is iterated through.

function getSectionTotalPages(section) {

 //entry point into JSON variable..Accessing sections attribue, which is an array
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 //loop through each of the sections
 for(var i=0;i<arrSections.length;i++) {
  var currSection = arrSections[i];
  //we get the section for which we want to calculate the page total
  if(currSection.name==section) {
   //Now into category array from section
   var arrCategories = currSection.categories;
   
   //loop through the category array
   for(var j=0;j<arrCategories.length;j++) {
    var currCategory = arrCategories[j];
    //For each category, get the article list (array)
    var arrArticles = currCategory.articles;
    //loop through each article
    for(var k=0;k<arrArticles.length;k++) {
     var currArticle = arrArticles[k];
 
     //for each article, get the # of pages and add it to total
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   //This method works for one section, so break the loop, if the section is found
   break;
  }
 }
 return totalPages;
}
The complete HTML containing the javascripts is given below. On clicking the compare button, the compareSectionPages function is called. It internally,calls getSectionTotalPages function twice, for getting pages for 'Java Programming' section and 'Market Analysis' section.
<html>
<head>
  <title>JSON and Javascript example</title>
  <script type="text/javascript" src="/website_json.js" ></script>
  <script language="javascript" type="text/javascript">
  function getSectionTotalPages(section) {
 var arrSections = varSiteData.sections;
 var totalPages = 0;
 for(var i=0;i<arrSections.length;i++) {
  var currSection = arrSections[i];
  if(currSection.name==section) {
   var arrCategories = currSection.categories;
  for(var j=0;j<arrCategories.length;j++) {

    var currCategory = arrCategories[j];
    var arrArticles = currCategory.articles;
    for(var k=0;k<arrArticles.length;k++) {
     var currArticle = arrArticles[k];
     totalPages = totalPages + parseInt(currArticle.pages);
    }
   }
   break;
  }
 }
 return totalPages;
}

  function compareSectionPages() {
   var totalJavaPages = getSectionTotalPages('Java Programming');
 var totalMarketPages = getSectionTotalPages('Market Analysis');
   var result = "<table border='1'><tr><td>Java Programming</td><td>Market Analysis</td>

</tr><tr><td>"+totalJavaPages+"</td><td>"+totalMarketPages+"</td></tr></table>";
   document.getElementById('result').innerHTML = result;
  }

  </script>
</head>
<body>
  <h2>Welcome to JSON with javascript workshop!</h2>
  <p>
  <input type="button" name="button1" value="Compare Section pages" onclick="compareSectionPages();">

  <p><p>
  Result: <div id="result"></div>
</body>
</html>

 And the result is 17 to 12. Java programming wins by 5 goals!

The author of the 'Market analysis' section may feel bit hard done by.  Some articles missed out were missed out. 'Technical Analysis' and 'Market Summary' articles were not considered. We added every article inside the category, but these two articles are not maintained at category level. They are maintained in section level.