How to check if JavaScript object is JSON

Posted by Wei Hao on Stack Overflow See other posts from Stack Overflow or by Wei Hao
Published on 2012-06-25T02:42:22Z Indexed on 2012/06/25 3:16 UTC
Read the original article Hit count: 305

Filed under:
|

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?

I tried using typeof and instanceof but both didn't seem to work, as typeof will return an object for both JSON object and array, and instanceof gives an error when I do obj instanceof JSON.

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)?

For example:

JSON

var data = {"hi":
             {"hello":
               ["hi1","hi2"]
             },
            "hey":"words"
           }

JavaScript

var jsonObj = JSON.parse(data);
var level1 = jsonObj.hi;
var text = jsonObj.hey;
var arr = level1.hello;
//how to check if level1 was formerly a JSON object?
//how to check if arr was formerly a JSON array?
//how to check if text is a string?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about JSON