1. 程式人生 > >js遞迴遍歷json所有資料

js遞迴遍歷json所有資料

//遞迴遍歷json所有資料

function getAllJson(jsons, name, sign) {
    if(name == "" || name == undefined) {
        name = "json"
    }
    for(key in jsons) {
        var k = name + sign + key;
        if(!(jsons[key] instanceof Object)){
            console.log(k + " = " + jsons[key]); //如果不是Object則列印鍵值
}else{ getAllJson(jsons[key], k, sign); //如果是Object則遞迴 } } };

呼叫:

//json
var jsons = {
    "text": "ceshi",
    "id": 1234,
    "detail": 
    {
        "comp": "MXCHIP.Inc",
        "from": "ShangHai",
        "focus": "Internet",
        "module": 
        [
            {
                "k3"
: "EMW3165" }, { "k4": "EMW3166" }, { "k5": "EMW3031" }, { "k6": "EMW3239" } ], "good":"asfwe" }, "end":"asfda" } //呼叫 getAllJson(jsons, "", ">"
); //列印結果: /* json>text = ceshi index.html?__hbt=1531125872056:47 json>id = 1234 index.html?__hbt=1531125872056:47 json>detail>comp = MXCHIP.Inc index.html?__hbt=1531125872056:47 json>detail>from = ShangHai index.html?__hbt=1531125872056:47 json>detail>focus = Internet index.html?__hbt=1531125872056:47 json>detail>module>0>k3 = EMW3165 index.html?__hbt=1531125872056:47 json>detail>module>1>k4 = EMW3166 index.html?__hbt=1531125872056:47 json>detail>module>2>k5 = EMW3031 index.html?__hbt=1531125872056:47 json>detail>module>3>k6 = EMW3239 index.html?__hbt=1531125872056:47 json>detail>good = asfwe index.html?__hbt=1531125872056:47 json>end = asfda */