In this article I am going to explain how to read JSON with JavaScript. The basic part of the JSON is JsonElement. There are 4 types JSON elements.
  1. Json Object : Surrounded with curly braces and have child JSON elements
  2. Json Primitive Element : It contains field name and it's value
  3. Json Array Element : It contains field name and array of JSON elements.
  4. Json Null Element : It contains nothing 

Program Flow

Program flow for JSON reading is shown in the below diagram. 
  1. If element is JSON Object then iterate it into field names and JSON elements and process those JSON elements. 
  2. If element is JSON Array then iterate it into JSON elements and process those JSON elements.
  3. If element is JSON Primitive then print its value as String




JavaScript Code :

In the below example there are 4 JSON input strings, First 3 are normal JSON String, Fourth-one is Array.
checkIt - Is for to check the Object Type
readObject - Is for reading JSON Object
readArray - Is for reading JSON Array

   var object = {
        "age":23,
        "name":"srinivas",
        "blog":"http://blog.sodhanalibrary.com",
        "messages":["msg1","msg2","msg3"] 
    };

    var arrayConstructor = [].constructor;
    var objectConstructor = {}.constructor;

    var html='';

    checkIt(object);

    function checkIt(object) {
      if (object === null) {
        html += "\n\nnull \n";
      }
      else if (object === undefined) {
          html += "\n\nundefined \n";
      }
      else if (object.constructor === arrayConstructor) {
          html += "\n\nArray :: \n";
          readArray(object);
      }
      else if (object.constructor === objectConstructor) {
          readObject(object);
      }
      else {
         html += "\n\nPrimitive Datatype :: \n";
         html += object;
      }
    }
             

    function readObject(myobj) {
      html += "\n\nObject :: \n";
      html += myobj;
      for (key in myobj) {
        if (myobj.hasOwnProperty(key)) {
            html += "\n\nKey Value Pair :: \n";
            html += key + " = " + myobj[key];
            checkIt(myobj[key]);
        }
      }  
    }

    function readArray(myobj) {
      var n = myobj.length;
      html += myobj;
      for(var i=0;i<n;i++) {
        checkIt(myobj[i]);
        html += myobj[i];
      }
    }
    document.getElementById("jsonObject").innerHTML = html;

0 comments:

Blogroll

Follow this blog by Email

Popular Posts