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
*/

猜你喜欢

转载自blog.csdn.net/stone10086/article/details/80974157