javascript变量json对象等到路径

  javascript递归迭代json对象,得到每个遍历到的项目的路径,示例代码如下

注意json对象和数组的区分,具体参考这篇文章:javascript如何区分JSON对象或者[]数组

<script type="text/javascript">
    var json = [{
        "name": "zhansan",
        "age": 23,
        "address": {
            "city": "beijing",
            "year": [{ test: "气态流出物月报" }, [0, [1, 1]], 1],
            "gas": {
                "gasSheet": "气态流出物月报",
                "H_adjust": 1
            },
            "time": {
                "year": ["气态流出物月报", 0, 1],
                "start": [1, "~"],
                "duration": 31
            }
        },
        "units": { "title": "function" },    //怎么判断它是相对于根的子节点?
        "student": [13, "s1", "s2"]
    }, { abc: 123}];
    function IsArray(o) { var _o = {}; return _o.toString.call(o) == '[object Array]' }
    function RecursionJson(json, path) {
        var isArray = IsArray(json); //防止JSON对象定义了length对象,所以判断数组不要通过对象的length属性判断
        for (var attr in json)
            if (typeof json[attr] == 'object') {
                if (IsArray(json[attr])) {
                    for (var j = 0; j < json[attr].length; j++) {
                        if (typeof json[attr][j] == 'object')
                            RecursionJson(json[attr][j], path + (isArray ? '[' : '.') + attr + (isArray ? ']' : '') + '[' + j + ']'); //不是普通类型,递归遍历
                        else alert(path + (isArray ? '[' : '.') + attr + (isArray ? ']' : '') + '[' + j + ']:' + json[attr][j]);
                    }
                }
                else RecursionJson(json[attr], path + (isArray ? '[' : '.') + attr + (isArray ? ']' : '')); //递归遍历
            }
            else alert(path + (isArray ? '[' : '.') + attr + (isArray ? ']' : '') + ':' + json[attr]);
    }
    RecursionJson(json, "json");
 
</script> 

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:javascript变量json对象等到路径

评论(0)Web开发网
阅读(171)喜欢(0)JavaScript/Ajax开发技巧