Broad Network


JSON File

Forward: In this article, I explain the meaning of JSON File of JavaScript or ECMAScript.

By: Chrysanthus Date Published: 9 Aug 2012

Introduction

A JSON file is a file at a web server having just a JavaScript object literal (see below). The content of this file is normally downloaded by Ajax to the client browser. At the client browser it is assigned to a JavaScript global variable, and so forming a JavaScript object by “literal notation”. JavaScript code residing at the client browser can then use the properties and methods in the downloaded JSON file.

Note: If you cannot see the code or if you think anything is missing (broken link), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what has been typed.

JavaScript object by Literal Notation
Consider the following statement:

                   var myVar = “good”;

The right operand of the above statement is a string literal. The left operand is the declaration of a variable. The string literal is assigned to the variable. In a similar way you can have an object literal assigned to a variable. The syntax is,

           var myObject = {properties and methods};

Here the left operand is the declaration of a variable, which is the name of the object. The right operand consists of properties and methods of the object enclosed in curly brackets. The right operand is the object literal.

Object Literal Example
The following code is an XHTML document that has an object by literal notation:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
  </head>
  <body>
    <script type="text/javascript">
    
    myObj = {
                        x:2,
                        y:3,
                        addMtd:function ()
                                         {
                                             return (this.x + this.y)
                                         },
                        multMtd:function ()
                                          {
                                              return (this.addMtd() * this.addMtd())
                                          }
                   }

              answer = myObj.multMtd();

    </script>
    <button type="button" onclick="alert(answer)">Click</button>
  </body>
</html>

I have published an article titled, Creating JavaScript Objects by Literal Notation. You might want to read that article first in order to better understand JavaScript Objects by Literal Notation. In this article I concentrate on the nature and use of the JSON file.

In the above code, the object has two properties and two methods. The name of the first property is, x; it holds the number, 2. The name of the second property is, y; it holds the number, 3. The name of the first method, is addMtd; it adds the two numbers. The name of the second method is, multMtd; it squares the sum of the two numbers (using the multMtd method definition).

So when the multMtd method is called, it returns the square of the sum of the two numbers. It does this by calling the addMtd method twice and multiplying the results from the addMtd method. Remember, the addMtd method adds the two numbers.

After the object in the code, you have the statement,

      answer = myObj.multMtd();

This statement calls the multMtd method and assigns the result (square of sum of numbers) to the new variable, answer.

There is a button in the code. When you click the button, the value of the answer is displayed (at the browser).

The JSON file
A JSON file is a file at the server. The name of the file has the extension, “.json”. The content of the file is the right operand of a JavaScript object by literal notation. We can make the right operand of the above object the content of a JSON file. In this case, the content of the JSON file will simple be:

{
      x:2,
      y:3,
      addMtd:function ()
                       {
                           return (this.x + this.y)
                       },
      multMtd:function ()
                        {
                            return (this.addMtd() * this.addMtd())
                        }
}

So if the above is the content of your JSON file, then the XHTML document will become,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
  </head>
  <body>
    <script type="text/javascript">
    
    myObj = "";

    //Ajax code to download and assign the

    function answer ()
      {
        return myObj.multMtd();
      }

    </script>
    <button type="button" onclick="alert(answer)">Click</button>
  </body>
</html>

There are three things to note about your reulting XHTML document. The first one is that the global object variable name does not have the object literal assigned to it. It has but an empty string assigned to it. It is good to always assign an empty string to it. Remember, the object literal is now in a JSON file. The next thing is that there is an Ajax code (the details have not been shown). This Ajax code downloads the Ajax literal and assigns it to the global object variable name.

The last thing to note about our new XHTML document is that the single line statement that called the multMtd method of the object is now a function, “function answer ()”. Just accept the first and the last changes said without explanation. Explaining these points is a subject of a different article.

The Ajax Code
This is the last thing we shall talk about in this article. Here is an example of the Ajax code for the above situation:

    function ajaxFn()
    {
      var xmlHttp;
        
      try
        {
          // Firefox, Opera 8.0+, Safari
          xmlHttp = new XMLHttpRequest();   
        }
      catch (e)
        {
          // Internet Explorer    
          try
            {
              xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
          catch (e)
            {    
             try
              {        
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
              }
             catch (e)
              {        
                alert("Your browser does not support AJAX!");
              }
            }
        }
  
      xmlHttp.onreadystatechange=function()
        {
          if (xmlHttp.readyState == 4)
           {
              if (xmlHttp.status == 200)
                {
                   myObj = eval("(" + xmlHttp.responseText + ")");
                }
           }
         else
          {
            //report error – to the client.
          }
        }
  
      xmlHttp.open("GET","http://localhost/obj.json",true);
      xmlHttp.send(null);
    }
  
    ajaxFn();

You can use this code in your own project. All you have to do is to change the URL, “http://localhost/obj.json” to your own URL that has your JSON file. I will not explain the operation of the Ajax code; I have written two articles titled, “Making Ajax Request” and “Receiving Response to Ajax Request”. You can read these articles to understand the operation of the above Ajax code.

Advantages of a JSON File
A JSON file can be used as a JavaScript module. A module is a piece of code you can use for many programs. In the case of web sites, you can have a module that would be used for many JavaScript web pages (in different web sites). Know that you can have a module (JSON file) where methods would be calling one another. In the above example, the multMtd method calls the addMtd method.

The story does not end there. Programmers keep increasing the amount of JavaScript code we put in a web page. A very long JavaScript slows down the downloading process of the web page. You can reduce the length of the web page by keeping a lot of your JavaScript code in a JSON file. When you download a short web page, it will come to the client fast. As soon as the web page is displayed at the client browser, Ajax would download the JSON file and make the code of the JSON file available to the web page. By the time the user wants to start using the JavaScript of the web page, the JavaScript module (JSON file) would have been downloaded, unknown to the user. In this way, the user will think the web page has been downloaded fast. This is an example of what we call Active Client Pages (see later).

Conclusion
A JSON file is a file at a web server having just a JavaScript object literal. The name of this file has the extension, “.json”. The content of the file is downloaded by Ajax to the client browser. At the client browser it is assigned to a JavaScript global variable, and so forming a JavaScript object by “literal notation”. JavaScript code residing at the client browser can then use the properties and methods in the downloaded JSON file. A JSON file can offer modularization and increases the downloading speed of your web page.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course

Comments

Become the Writer's Fan
Send the Writer a Message