我有一个需要循环通过的嵌套JSON对象,每个键的值可以是String,JSON数组或另一个JSON对象。根据对象的类型,我需要执行不同的操作。有什么方法可以检查对象的类型以查看它是String,JSON对象还是JSON数组?
我尝试使用typeof和,instanceof但似乎都没有用,因为这typeof将为JSON对象和数组都返回一个对象,并且instanceof在我这样做时给出错误obj instanceof JSON。
typeof
instanceof
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 } }
如何执行上述对象检查?
我会检查构造函数属性。
例如
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])); }
编辑:添加了一个空检查和一个未定义的检查。