JS判断json有哪些方法

JavaScript026

JS判断json有哪些方法,第1张

function isJSON(str) {

if (typeof str == 'string') {

try {

var obj=JSON.parse(str)

if(typeof obj == 'object' &&obj ){

return true

}else{

return false

}

} catch(e) {

console.log('error:'+str+'!!!'+e)

return false

}

}

console.log('It is not a string!')

}

先将JSON数组转换成对象

JSON.parse(jsonData)

然后使用 'name' in obj 如果为true 则有这个节点。

或者使用 typeof obj['属性名'] 如果为 undefined 则没有这个节点。

注意: 这两种方式都只能判断一级对象, 如果是多级树型结构只能使用递归去判断了,