我有一个需要循环的嵌套 JSON 对象,每个键的值可以是字符串、JSON 数组或另一个 JSON 对象。根据对象的类型,我需要执行不同的操作。有什么方法可以检查对象的类型,看它是字符串、JSON 对象还是 JSON 数组?
我尝试使用 typeof
和 instanceof
但两者似乎都不起作用,因为 typeof
将为 JSON 对象和数组,当我执行 obj instanceof JSON
时,instanceof
会出错。
更具体地说,在将 JSON 解析为 JS 对象后,有什么方法可以检查它是普通字符串,还是带有键和值的对象(来自 JSON 对象),还是数组(来自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
}
}
如上所示,如何进行对象检查?
最佳答案
我会检查构造函数属性。
例如
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]));
}
编辑:添加了一个空检查和一个未定义的检查。
https://stackoverflow.com/questions/11182924/