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,"",">")
輸出結果如下:
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