title: How to check if JavaScript object is JSON
body: <p>I have a nested JSON object that I need to loop through, and the value of each key could be a String, JSON array or another JSON object. Depending on the type of object, I need to carry out different operations. Is there any way I can check the type of the object to see if it is a String, JSON object or JSON array?</p>
  
  <p>I tried using <code>typeof</code> and <code>instanceof</code> but both didn't seem to work, as <code>typeof</code> will return an object for both JSON object and array, and <code>instanceof</code> gives an error when I do <code>obj instanceof JSON</code>.</p>
  
  <p>To be more specific, after parsing the JSON into a JS object, is there any way I can check if it is a normal string, or an object with keys and values (from a JSON object), or an array (from a JSON array)?</p>
  
  <p>For example:</p>
  
  <p>JSON</p>
  
  <pre><code>var data = "{'hi':
               {'hello':
                 ['hi1','hi2']
               },
              'hey':'words'
             }";
  </code></pre>
  
  <p>Sample JavaScript</p>
  
  <pre><code>var jsonObj = JSON.parse(data);
  var path = ["hi","hello"];
  
  function check(jsonObj, path) {
      var parent = jsonObj;
      for (var i = 0; i &lt; path.length-1; i++) {
          var key = path[i];
          if (parent != undefined) {
              parent = parent[key];
          }
      }
      if (parent != undefined) {
          var endLength = path.length - 1;
          var child = parent[path[endLength]];
          //if child is a string, add some text
          //if child is an object, edit the key/value
          //if child is an array, add a new element
          //if child does not exist, add a new key/value
      }
  }
  </code></pre>
  
  <p>How do I carry out the object checking as shown above?</p>