{"id":77,"date":"2013-01-20T05:10:11","date_gmt":"2013-01-20T05:10:11","guid":{"rendered":"http:\/\/localhost\/tfcom_wp\/2013\/01\/20\/json-javascript\/"},"modified":"2025-06-30T02:42:16","modified_gmt":"2025-06-30T02:42:16","slug":"json-javascript","status":"publish","type":"post","link":"https:\/\/www.tech-freaks.com\/java\/javascript\/json-javascript.html","title":{"rendered":"Javascript with JSON"},"content":{"rendered":"<p style=\"text-align: left;\"><strong>This workshop is for you, if:<\/strong><\/p>\n<ul style=\"text-align: left;\">\n<li>You are looking for a data structure to store your data for easy javascript access<\/li>\n<li>You have seen JSON structure but do not know, how to access it using javascript<\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong>This workshop is not for you, if:<\/strong><\/p>\n<ul style=\"text-align: left;\">\n<li>You have no idea about client side scripting<\/li>\n<\/ul>\n<p style=\"text-align: left;\">This workshop intends to provide hands on example on creating JSON structure and accessing the contents of the JSON using Javascript.<\/p>\n<p style=\"text-align: left;\"><strong>&#8216;JSON&#8217; the new kid in town<\/strong><\/p>\n<p style=\"text-align: left;\">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.<\/p>\n<ul style=\"text-align: left;\">\n<li>JSON can store data in the client side, where data security is not important.<\/li>\n<li>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.<\/li>\n<\/ul>\n<p style=\"text-align: left;\"><strong>Workshop Requirement<\/strong><\/p>\n<p style=\"text-align: left;\">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.<\/p>\n<p style=\"text-align: left;\"><strong>Meeting JSON flesh and blood<\/strong><\/p>\n<p style=\"text-align: left;\">Enough talking about JSON! Let us actually see a JSON structure. The\u00a0code snippet provided\u00a0below\u00a0shows 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 &#8216;eval&#8217; function, which is not recommended. There are parsers available in\u00a0<a title=\"www.json.org\" href=\"http:\/\/www.json.org\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\"><span style=\"text-decoration: underline;\"><span style=\"color: #800080;\">JSON.org<\/span><\/span><\/a>\u00a0which converts the JSON structure to javascript variable.<\/p>\n<pre class=\"language-javascript\"><code>var varSiteData = {\n  \"sections\" : [ \/\/Array\n     {\/\/Each element in array, ie. Section is a structure not a simple attribute\n      \"name\": \"Java Programming\", \/\/this is a simple attribute\n      \"categories\": [\n      {\n         \"name\":\"Java Basics\",\n         \"articles\": [\n         {\n            \"name\" : \"Java Hello World\",\n            \"pages\" : \"1\",\n            \"author\" : \"Tech Programmer\"         \n         },\n         {\n            \"name\" : \"Java Hello World using Eclipse IDE\",\n            \"pages\" : \"5\",\n            \"author\" : \"Tech Programmer\"         \n         },\n         ...\n         ...\n       ]\n      },\n      ...\n      ...\n     ]\n    },\n    ...\n    ....\n   ]\n }<\/code><\/pre>\n<pre class=\"code-style\" style=\"text-align: left;\"><\/pre>\n<p style=\"text-align: left;\">Let us try to understand the syntax. JSON always start and end with curly braces.\u00a0They contain\u00a0attributes. 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 &#8220;section&#8221; 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 &#8220;name&#8221;. Attribute &#8220;name&#8221; is a simple string. Other attributes shown work in the same way. Click\u00a0<a title=\"JSON in JS\" href=\"sourcecode\/JSON\/v1\/website_json.js\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">here<\/a>\u00a0to download the complete JSON structure stored in JS file.<\/p>\n<dl id=\"tf-message\">\n<dd class=\"message message fade\">\n<ul>\n<li>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: &#8220;str_25&#8221;<\/li>\n<\/ul>\n<\/dd>\n<\/dl>\n<p style=\"text-align: left;\">\u00a0One 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:<\/p>\n<pre class=\"language-javascript\"><code>\"alphonsa\" : {\n  \"type\": \"mango\",\n  \"taste\": \"sweet\",\n  \"color\": \"yellow\"\n}<\/code><\/pre>\n<p style=\"text-align: left;\">Well, that&#8217;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.<\/p>\n<pre class=\"language-markup\"><code>&lt;?xml version=\"1.0\" encoding=\"ISO-8859-1\"?&gt;\n&lt;sections&gt;\n  &lt;section&gt;\n     &lt;name&gt;Java Programming&lt;\/name&gt;\n     &lt;category&gt;\n        &lt;name&gt;Java Basics&lt;\/name&gt;\n        &lt;article&gt;\n           &lt;name&gt;Java Hello World&lt;\/name&gt;\n           &lt;pages&gt;1&lt;\/pages&gt;\n           &lt;author&gt;Tech Programmer&lt;\/author&gt;\n        &lt;\/article&gt;\n        &lt;article&gt;\n           &lt;name&gt;Java Hello World using Eclipse IDE&lt;\/name&gt;\n           &lt;pages&gt;5&lt;\/pages&gt;\n           &lt;author&gt;Tech Programmer&lt;\/author&gt;\n        &lt;\/article&gt;\n       ...\n       ...\n     &lt;\/category&gt;\n  &lt;\/section&gt;\n..\n&lt;\/sections&gt;<\/code><\/pre>\n<p style=\"text-align: left;\"><strong>Validating JSON structure<\/strong><\/p>\n<p style=\"text-align: left;\">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.\u00a0<a title=\"JSON Viewer\" href=\"http:\/\/www.codeplex.com\/JsonViewer\" target=\"_blank\" rel=\"nofollow noopener noreferrer\"><span style=\"text-decoration: underline;\"><span style=\"color: #800080;\">JSON Viewer<\/span><\/span><\/a>\u00a0is one such hand helpful too.<\/p>\n<p style=\"text-align: left;\"><strong>Javascript and JSON<\/strong><\/p>\n<p style=\"text-align: left;\">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 &#8216;Stock Market&#8217; and &#8216;Java Programming&#8217; 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.<\/p>\n<p style=\"text-align: left;\">See the below javascript function, with comments explaining how the JSON structure is iterated through.<\/p>\n<pre class=\"language-javascript\"><code>function getSectionTotalPages(section) {\n\n \/\/entry point into JSON variable..Accessing sections attribue, which is an array\n var arrSections = varSiteData.sections;\n var totalPages = 0;\n \/\/loop through each of the sections\n for(var i=0;i&lt;arrSections.length;i++) {\n  var currSection = arrSections[i];\n  \/\/we get the section for which we want to calculate the page total\n  if(currSection.name==section) {\n   \/\/Now into category array from section\n   var arrCategories = currSection.categories;\n   \n   \/\/loop through the category array\n   for(var j=0;j&lt;arrCategories.length;j++) {\n    var currCategory = arrCategories[j];\n    \/\/For each category, get the article list (array)\n    var arrArticles = currCategory.articles;\n    \/\/loop through each article\n    for(var k=0;k&lt;arrArticles.length;k++) {\n     var currArticle = arrArticles[k];\n \n     \/\/for each article, get the # of pages and add it to total\n     totalPages = totalPages + parseInt(currArticle.pages);\n    }\n   }\n   \/\/This method works for one section, so break the loop, if the section is found\n   break;\n  }\n }\n return totalPages;\n}<\/code><\/pre>\n<pre class=\"brush:javascript\" style=\"text-align: left;\"><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">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 <\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">'<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">Java Programming<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">'<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\"> section and <\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">'<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">Market Analysis<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\">'<\/span><span style=\"font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; font-size: 1rem;\"> section.<\/span><\/pre>\n<pre class=\"language-markup\"><code>&lt;html&gt;\n&lt;head&gt;\n  &lt;title&gt;JSON and Javascript example&lt;\/title&gt;\n  &lt;script type=\"text\/javascript\" src=\"website_json.js\" &gt;&lt;\/script&gt;\n  &lt;script language=\"javascript\" type=\"text\/javascript\"&gt;\n  function getSectionTotalPages(section) {\n var arrSections = varSiteData.sections;\n var totalPages = 0;\n for(var i=0;i&lt;arrSections.length;i++) {\n  var currSection = arrSections[i];\n  if(currSection.name==section) {\n   var arrCategories = currSection.categories;\n  for(var j=0;j&lt;arrCategories.length;j++) {\n\n    var currCategory = arrCategories[j];\n    var arrArticles = currCategory.articles;\n    for(var k=0;k&lt;arrArticles.length;k++) {\n     var currArticle = arrArticles[k];\n     totalPages = totalPages + parseInt(currArticle.pages);\n    }\n   }\n   break;\n  }\n }\n return totalPages;\n}\n\n  function compareSectionPages() {\n   var totalJavaPages = getSectionTotalPages('Java Programming');\n var totalMarketPages = getSectionTotalPages('Market Analysis');\n   var result = \"&lt;table border='1'&gt;&lt;tr&gt;&lt;td&gt;Java Programming&lt;\/td&gt;&lt;td&gt;Market Analysis&lt;\/td&gt;\n\n&lt;\/tr&gt;&lt;tr&gt;&lt;td&gt;\"+totalJavaPages+\"&lt;\/td&gt;&lt;td&gt;\"+totalMarketPages+\"&lt;\/td&gt;&lt;\/tr&gt;&lt;\/table&gt;\";\n   document.getElementById('result').innerHTML = result;\n  }\n\n  &lt;\/script&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n  &lt;h2&gt;Welcome to JSON with javascript workshop!&lt;\/h2&gt;\n  &lt;p&gt;\n  &lt;input type=\"button\" name=\"button1\" value=\"Compare Section pages\" onclick=\"compareSectionPages();\"&gt;\n\n  &lt;p&gt;&lt;p&gt;\n  Result: &lt;div id=\"result\"&gt;&lt;\/div&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/code><\/pre>\n<p style=\"text-align: left;\">\u00a0And the result is 17 to 12. Java programming wins by 5 goals!<\/p>\n<p style=\"text-align: left;\">The author of the &#8216;Market analysis&#8217; section may feel bit hard done by.\u00a0 Some articles missed out were missed out. &#8216;Technical Analysis&#8217; and &#8216;Market Summary&#8217; 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.<\/p>\n<hr class=\"system-pagebreak\" title=\"JSON flexibility\" \/>\n<p style=\"text-align: left;\">Well, change is inevitable in the JSON structure! However, the flexibility of JSON will cover up for it. But, the change in data structure will cause a change to javascript code to calculate the total pages in section.<\/p>\n<p style=\"text-align: left;\">Let us get this thing fixed. For the JSON fix, a little thought will make it clear that adding articles inside section structure will be similar to articles maintained inside categories. The below code snippet shows the portion of the changed JSON:<\/p>\n<pre class=\"code-style\" style=\"text-align: left;\"><\/pre>\n<pre class=\"language-javascript\"><code> ...\n      {\n      \"name\":\"Market Analysis\",\n      \"articles\": [\n       {\n          \"name\": \"Market Summary\",\n          \"pages\": \"1\",\n          \"author\" : \"Market Analyst\"        \n       },\n       {\n          \"name\": \"Tech Analysis\",\n          \"pages\": \"1\",\n          \"author\" : \"Market Analyst\"        \n       }\n      ] \n      ....\n     .....<\/code><\/pre>\n<p style=\"text-align: left;\">The change in\u00a0 getSectionTotalPages will be bit more challenging. Now, in the code we have to deal with one section, which has articles array and another which does not. Also, this method needs to be generic enough to handle any new sections added to the website in the future. Some of the section may have articles inside it and some may not. Many times, while using javascript we see the &#8216;undefined&#8217; variable. We will have to use this, to check if articles array is present directly within sections.<\/p>\n<p>The below modified function getSectionTotalPages will do the trick. See the comments explaining the main changes and\u00a0the\u00a0<em>typeof<\/em>\u00a0function used to good effect.<\/p>\n<pre class=\"language-javascript\"><code>function getSectionTotalPages(section) {\n var arrSections = varSiteData.sections;\n var totalPages = 0;\n for(var i=0;i&lt;arrSections.length;i++) {\n  var currSection = arrSections[i];\n  if(currSection.name==section) {\n   \/\/Check if articles inside section is undefined (does not exist)\n   \/\/If not undefined, then section as articles like Market Analysis section\n   if(typeof(currSection.articles)!='undefined') {\n\n    var arrSecArticles = currSection.articles;\n    for(var j=0;j&lt;arrSecArticles.length;j++) {\n     var currSecArticle = arrSecArticles[j];\n     totalPages = totalPages + parseInt(currSecArticle.pages);\n\n    }\n   }\n   var arrCategories = currSection.categories;\n\n   for(var j=0;j&lt;arrCategories.length;j++) {\n    var currCategory = arrCategories[j];\n    var arrArticles = currCategory.articles;\n    for(var k=0;k&lt;arrArticles.length;k++) {\n     var currArticle = arrArticles[k];\n     totalPages = totalPages + parseInt(currArticle.pages);\n    }\n   }\n   break;\n  }\n }\n return totalPages;\n}<\/code><\/pre>\n<p style=\"text-align: left;\">Update the HTML code contents with the above updated function. Click <span style=\"text-decoration: underline;\"><span style=\"color: #0066cc;\"><a title=\"JSON structure\" href=\"sourcecode\/JSON\/v2\/website_json.js\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">here<\/a><\/span><\/span>\u00a0to download the updated JSON code. Place the HTML and JS file in the same directory. Access the HTML page from browser and then click the &#8216;Compare Section pages&#8217; button to view the result table. &#8216;Java Programming&#8217; still wins by a margin of 3!<\/p>\n<p style=\"text-align: left;\">Welcome to the whole new world of client side scripting with JSON!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This workshop is for you, if: You are looking for a data structure to store your data for easy javascript [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[7],"tags":[],"class_list":["post-77","post","type-post","status-publish","format-standard","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/77","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/comments?post=77"}],"version-history":[{"count":1,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/77\/revisions"}],"predecessor-version":[{"id":146,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/77\/revisions\/146"}],"wp:attachment":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media?parent=77"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/categories?post=77"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/tags?post=77"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}