126

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'
           }";

Sample JavaScript

var jsonObj = JSON.parse(data);
var path = ["hi","hello"];

function check(jsonObj, path) {
    var parent = jsonObj;
    for (var i = 0; i < 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
    }
}

How do I carry out the object checking as shown above?

Wei Hao
  • 2,756
  • 9
  • 27
  • 40

19 Answers19

160

I'd check the constructor attribute.

e.g.

var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.

Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
Programming Guy
  • 7,259
  • 11
  • 50
  • 59
  • 10
    `else if` is unnecessary – McSonk Apr 30 '17 at 18:46
  • Is not this the same as using instanceof? https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/instanceof – Pereira Sep 23 '18 at 16:50
  • @Pereira: JavaScript has some confusing wrinkles. Try "surely_this_is_a_string" instanceof String. – Programming Guy Sep 24 '18 at 23:45
  • `{}.constructor` is causing me to get `ERROR TypeError: Cannot read property 'constructor' of undefined` in my angular application. – kebab-case Aug 09 '19 at 20:36
  • @Minyc510 : Looks like browser behaviour has changed. Wrapping in brackets seems to fix it. I've edited the answer to reflect this. – Programming Guy Aug 12 '19 at 00:08
  • 2
    So many `if` statements... Use a [`switch`](https://www.w3schools.com/js/js_switch.asp)! – Nanoo Sep 08 '20 at 18:51
  • Nice answer - but absolutely ridiculous that there is no function to do this in JS – Enigma Plus Mar 03 '21 at 19:38
  • I don't feel that this answers the question. a string is a string, but a JSON object is ... also a string. So in my case, I need to check if any value is JSON before I call JSON.parse, so it doesn't blow up. My answer would be to use try-catch and just return false in the catch and true otherwise. – Urasquirrel Oct 20 '21 at 14:48
  • The question has been edited a few times, but the last paragraph still specifically requests determining object type after it has been parsed. – Programming Guy Oct 21 '21 at 22:28
35

You can use Array.isArray to check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.

var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
    if (Array.isArray(p)) return 'array';
    else if (typeof p == 'string') return 'string';
    else if (p != null && typeof p == 'object') return 'object';
    else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));

's' is string
'a' is array
'o' is object
'i' is other

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
27

An JSON object is an object. To check whether a type is an object type, evaluate the constructor property.

function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}

The same applies to all other types:

function isArray(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Array;
}

function isBoolean(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Boolean;
}

function isFunction(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Function;
}

function isNumber(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Number;
}

function isString(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == String;
}

function isInstanced(obj)
{
    if(obj === undefined || obj === null) { return false; }

    if(isArray(obj)) { return false; }
    if(isBoolean(obj)) { return false; }
    if(isFunction(obj)) { return false; }
    if(isNumber(obj)) { return false; }
    if(isObject(obj)) { return false; }
    if(isString(obj)) { return false; }

    return true;
}
Max Phillips
  • 6,991
  • 9
  • 44
  • 71
Martin Wantke
  • 4,287
  • 33
  • 21
  • 4
    JSON encoded resource is not an object. It is a string. Only after you decode it or in Javascript `JSON.parse()` it does the JSON resource become an object. Therefore if you test a resource coming from a server to see if it is JSON, it is best to check first for String, then if is a not a `` and then after parsing if it is an object. – Hmerman6006 Jun 03 '20 at 12:28
  • This is easiest way! Worked – Rohit Parte Nov 24 '22 at 07:39
10

you can also try to parse the data and then check if you got object:

try {
    var testIfJson = JSON.parse(data);
    if (typeof testIfJson == "object"){
        //Json
    } else {
        //Not Json
    }
}
catch {
    return false;
}
arielhad
  • 1,753
  • 15
  • 12
9

If you are trying to check the type of an object after you parse a JSON string, I suggest checking the constructor attribute:

obj.constructor == Array || obj.constructor == String || obj.constructor == Object

This will be a much faster check than typeof or instanceof.

If a JSON library does not return objects constructed with these functions, I would be very suspiciouse of it.

prayagupa
  • 30,204
  • 14
  • 155
  • 192
JoshRagem
  • 575
  • 3
  • 10
6

The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof

function isJson(obj) {
    var t = typeof obj;
    return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}
Dmitry Efimenko
  • 10,973
  • 7
  • 62
  • 79
5

You could make your own constructor for JSON parsing:

var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}

Then check instanceof to see if it needed parsing originally

test instanceof JSONObj
matt3141
  • 4,303
  • 1
  • 19
  • 24
4

I wrote an npm module to solve this problem. It's available here:

object-types: a module for finding what literal types underly objects

Install

  npm install --save object-types


Usage

const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

Dawson B
  • 1,224
  • 12
  • 16
4

Try, Catch block will help you to solve this

Make a function

function IsJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

Example:

console.log(IsJson('abc')) // false
console.log(IsJson('[{"type":"email","detail":"john@example.com"}]')) // true
3

Why not check Number - a bit shorter and works in IE/Chrome/FF/node.js

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    else if (object === undefined) {
        return "undefined";
    }
    if (object.constructor.name) {
            return object.constructor.name;
    }
    else { // last chance 4 IE: "\nfunction Number() {\n    [native code]\n}\n" / node.js: "function String() { [native code] }"
        var name = object.constructor.toString().split(' ');
        if (name && name.length > 1) {
            name = name[1];
            return name.substr(0, name.indexOf('('));
        }
        else { // unreachable now(?)
            return "don't know";
        }
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
// Test all options
console.log(whatIsIt(null));
console.log(whatIsIt());
for (var i=0, len = testSubjects.length; i < len; i++) {
    console.log(whatIsIt(testSubjects[i]));
}
Jan
  • 2,178
  • 3
  • 14
  • 26
2

I combine the typeof operator with a check of the constructor attribute (by Peter):

var typeOf = function(object) {
    var firstShot = typeof object;
    if (firstShot !== 'object') {
        return firstShot;
    } 
    else if (object.constructor === [].constructor) {
        return 'array';
    }
    else if (object.constructor === {}.constructor) {
        return 'object';
    }
    else if (object === null) {
        return 'null';
    }
    else {
        return 'don\'t know';
    } 
}

// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];

console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
    console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});

Result:

typeOf()    input parameter
---------------------------
boolean     true
boolean     false
number      1
number      2.3
string      "string"
array       [4,5,6]
object      {"foo":"bar"}
null        null
undefined       
2

I know this is a very old question with good answers. However, it seems that it's still possible to add my 2¢ to it.

Assuming that you're trying to test not a JSON object itself but a String that is formatted as a JSON (which seems to be the case in your var data), you could use the following function that returns a boolean (is or is not a 'JSON'):

function isJsonString( jsonString ) {

  // This function below ('printError') can be used to print details about the error, if any.
  // Please, refer to the original article (see the end of this post)
  // for more details. I suppressed details to keep the code clean.
  //
  let printError = function(error, explicit) {
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
  }


  try {
      JSON.parse( jsonString );
      return true; // It's a valid JSON format
  } catch (e) {
      return false; // It's not a valid JSON format
  }

}

Here are some examples of using the function above:

console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );

console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );

console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );

console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );

console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );

console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );

console.log('\n7 -----------------');
j = '[{"a":1, "b":   2}, {"c":3}]';
console.log( j, isJsonString(j) );

When you run the code above, you will get the following results:

1 -----------------
abc false

2 -----------------
{"abc": "def"} true

3 -----------------
{"abc": "def} false

4 -----------------
{} true

5 -----------------
[{}] true

6 -----------------
[{},] false

7 -----------------
[{"a":1, "b":   2}, {"c":3}] true

Please, try the snippet below and let us know if this works for you. :)

IMPORTANT: the function presented in this post was adapted from https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing where you can find more and interesting details about the JSON.parse() function.

function isJsonString( jsonString ) {

  let printError = function(error, explicit) {
  console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
  }


  try {
      JSON.parse( jsonString );
      return true; // It's a valid JSON format
  } catch (e) {
      return false; // It's not a valid JSON format
  }

}


console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );

console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );

console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );

console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );

console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );

console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );

console.log('\n7 -----------------');
j = '[{"a":1, "b":   2}, {"c":3}]';
console.log( j, isJsonString(j) );
Almir Campos
  • 2,833
  • 1
  • 30
  • 26
1

Try this

if ( typeof is_json != "function" )
function is_json( _obj )
{
    var _has_keys = 0 ;
    for( var _pr in _obj )
    {
        if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
        {
           _has_keys = 1 ;
           break ;
        }
    }

    return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}

It works for the example below

var _a = { "name" : "me",
       "surname" : "I",
       "nickname" : {
                      "first" : "wow",
                      "second" : "super",
                      "morelevel" : {
                                      "3level1" : 1,
                                      "3level2" : 2,
                                      "3level3" : 3
                                    }
                    }
     } ;

var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;

console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );
Sandro Rosa
  • 507
  • 4
  • 12
1

Based on @Martin Wantke answer, but with some recommended improvements/adjusts...

// NOTE: Check JavaScript type. By Questor
function getJSType(valToChk) {

    function isUndefined(valToChk) { return valToChk === undefined; }
    function isNull(valToChk) { return valToChk === null; }
    function isArray(valToChk) { return valToChk.constructor == Array; }
    function isBoolean(valToChk) { return valToChk.constructor == Boolean; }
    function isFunction(valToChk) { return valToChk.constructor == Function; }
    function isNumber(valToChk) { return valToChk.constructor == Number; }
    function isString(valToChk) { return valToChk.constructor == String; }
    function isObject(valToChk) { return valToChk.constructor == Object; }

    if(isUndefined(valToChk)) { return "undefined"; }
    if(isNull(valToChk)) { return "null"; }
    if(isArray(valToChk)) { return "array"; }
    if(isBoolean(valToChk)) { return "boolean"; }
    if(isFunction(valToChk)) { return "function"; }
    if(isNumber(valToChk)) { return "number"; }
    if(isString(valToChk)) { return "string"; }
    if(isObject(valToChk)) { return "object"; }

}

NOTE: I found this approach very didactic, so I submitted this answer.

Eduardo Lucio
  • 1,771
  • 2
  • 25
  • 43
0

Peter's answer with an additional check! Of course, not 100% guaranteed!

var isJson = false;
outPutValue = ""
var objectConstructor = {}.constructor;
if(jsonToCheck.constructor === objectConstructor){
    outPutValue = JSON.stringify(jsonToCheck);
    try{
            JSON.parse(outPutValue);
            isJson = true;
    }catch(err){
            isJson = false;
    }
}

if(isJson){
    alert("Is json |" + JSON.stringify(jsonToCheck) + "|");
}else{
    alert("Is other!");
}
Eduardo Lucio
  • 1,771
  • 2
  • 25
  • 43
0

I have a pretty lazy answer to this, which will not throw an error if you try to parse a string/other values.

const checkForJson = (value) => {
    if (typeof value !== "string") return false;

    return value[0] === "{" && value[value.length - 1] === "}";
}

You can use this to check the value of your keys while you make some recursive func; sorry if this doesn't answer the question completely

Ofc this isn't the most elegant solution and will fail when a string actually starts with "{" and ends with "}" although those use cases would be rare, and if you really wanted, you can check for a presence of quotes or other nonsense... anyway, use at your own discretion.

TLDR: it's not bulletproof, but it's simple and works for the vast majority of use cases.

ChronicLogic
  • 313
  • 3
  • 17
  • It will also not work if there is an array inside. Try with `JSON.parse(JSON.stringify(['a','b','c',1,2,3])))` – RiZKiT Nov 18 '21 at 13:15
0

lodash is also the best bet to check these things.

function Foo() {
  this.a = 1;
}
 
_.isPlainObject(new Foo);
// => false
 
_.isPlainObject([1, 2, 3]);
// => false
 
_.isPlainObject({ 'x': 0, 'y': 0 });
// => true
 
_.isPlainObject(Object.create(null));
// => true

https://www.npmjs.com/package/lodash
https://lodash.com/docs/#isPlainObject

Mohamed Jakkariya
  • 1,257
  • 1
  • 13
  • 16
0

Quickly check for a JSON structure using lodash-contrib:

const _ = require('lodash-contrib');

_.isJSON('{"car": "ferarri"}'); //true for stringified
_.isJSON({car: "ferarri"}); //true  

Usage guide: this blog entry

GavinBelson
  • 2,514
  • 25
  • 36
-5

try this dirty way

 ('' + obj).includes('{')
Stan Sokolov
  • 2,140
  • 1
  • 22
  • 23