我需要循环访问一个嵌套的 JSON 对象,每个键的值可以是一个 String、 JSON 数组或另一个 JSON 对象。根据对象的类型,我需要执行不同的操作。有没有什么办法可以检查对象的类型,看看它是一个字符串,JSON 对象或 JSON 数组?
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
.
更具体地说,在将 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
}
}
如何执行上面所示的对象检查?