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
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值