JavaScript递归遍历输出json所有字段与值的⽅法声明⼀个三层的json对象作为测试:
var js={
"text":"MXCHIP won a prize",
"id": 1234,
"detail":{
"comp": "MXCHIP.Inc",
"from":"ShangHai",
"focus":"Internet of Things",
"module":[{"k":"EMW3165"},{"k":"EMW3166"},{"k":"EMW3031"},{"k":"EMW3239"}]
}
}
递归取值函数:(key为键名,sign为各级别键名之间的分隔符)
function printValue(js,key,sign){
if(key == ""||key == undefined){
key="json"
}
for(p in js){
var k=key+sign+p
if(!(js[p] instanceof Object))
console.log(k+" = "+js[p])    //如果不是Object则打印键值
else
printValue(js[p],k,sign)    //如果是Object则递归
}
}
printValue(js,"",">")
js获取json的key和value输出结果如下:
json>text = MXCHIP won a prize json>id = 1234
json>detail>comp = MXCHIP.Inc json>detail>from = ShangHai
json>detail>focus = Internet of Things json>detail>module>0>k = EMW3165 json>detail>module>1>k = EMW3166 json>detail>module>2>k = EMW3031 json>detail>module>3>k = EMW3239

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。