【问题标题】:How to find depth of nodes in a nested json file?如何在嵌套的 json 文件中查找节点的深度?
【发布时间】:2020-05-24 01:51:32
【问题描述】:

我找到了许多解决方案来查找嵌套 json 文件中的节点深度。但它给我一个错误“超出最大递归深度” 当它设置最大递归限制时,它说“进程超出了一些错误代码” 作为我的问题的一部分,我还需要找出 json 文件中每个节点的键名。

示例 json :

"attachments": {
            "data": [
               {
                  "media": {
                     "image": {
                        "height": 400,
                        "src": "https://scontent.xx.fbcdn.net/v/t1.0-1/10250217_10152130974757825_8645405213175562082_n.jpg?oh=904c1785fc974a3208f1d18ac07d59f3&oe=57CED94D",
                        "width": 400
                     }
                  },
                  "target": {
                     "id": "74286767824",
                     "url": "https://www.facebook.com/LAInternationalAirport/"
                  },
                  "title": "Los Angeles International Airport (LAX)",
                  "type": "map",
                  "url": "https://www.facebook.com/LAInternationalAirport/"
               }
            ]
         }

输出应该是:

节点: [数据[媒体[图像[高度,宽度,src]],目标[id,url],标题,类型,url]]

深度:4

【问题讨论】:

    标签: json


    【解决方案1】:

    如果其他人来到这里并发现接受的答案不起作用,因为字符串的 Object.keys() 返回字符串的每个字符的数组,因此对于大对象或具有大字符串的对象,它只会失败。 这是可行的->

    function getDepth(obj){
        if(!obj || obj.length===0 || typeof(obj)!=="object") return 0;
        const keys = Object.keys(obj);
        let depth = 0;
        keys.forEach(key=>{
            let tmpDepth = getDepth(obj[key]);
            if(tmpDepth>depth){
                depth = tmpDepth;
            }
        })
        return depth+1;
    }
    

    示例 - https://jsfiddle.net/95g3ebp7/

    【讨论】:

      【解决方案2】:
      function geth(obj) {
        var depth = 0;
        var k = Object.keys(obj);
        console.log(k);
        for (var i in k) {
            var tmpDepth = geth(obj[k[i]]);
            if (tmpDepth > depth) {
                depth = tmpDepth
            }
        }
        return 1 + depth;
      }
      

      【讨论】:

      • 这将递归计算json树的深度
      • 由于它使用递归,它对于我的对象非常大且嵌套失败。可以有一种迭代方法吗?会有很大帮助的。
      • 如果对象包含单个字符串值,这将不起作用。这将导致无限递归。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2018-01-03
      • 2011-02-01
      • 1970-01-01
      • 2020-12-10
      相关资源
      最近更新 更多