如何检查 JavaScript 对象是否为 JSON

2022-08-30 05:37:39

我有一个需要循环遍历的嵌套JSON对象,每个键的值可以是字符串,JSON数组或其他JSON对象。根据对象的类型,我需要执行不同的操作。有没有办法检查对象的类型,以查看它是字符串,JSON对象还是JSON数组?

我尝试使用,但两者似乎都不起作用,因为将为JSON对象和数组返回一个对象,并在我这样做时给出错误。typeofinstanceoftypeofinstanceofobj instanceof JSON

更具体地说,在将JSON解析为JS对象之后,有没有办法检查它是普通字符串,还是具有键和值的对象(来自JSON对象),还是数组(来自JSON数组)?

例如:

断续器

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

示例 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
    }
}

如何执行如上所示的对象检查?


答案 1

我会检查构造函数属性。

例如:

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]));
}

编辑:添加了空检查和未定义的检查。


答案 2

您可以使用 Array.isArray 来检查数组。然后 typeof obj == 'string'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' 是字符串
'a' 是数组
'o' 是对象
'i' 是其他