4

您如何获得对象所有子节点的 JSONPath?

例如:

var data = [{
    "key1": {
        "children": [{
            "key2": "value",
            "key3": "value",
            "key4": {}
        }, {
            "key2": "value",
            "key3": "value",
            "key4": {}
        }],
        "key5": "value"
    }
}, {
    "key1": {
        "children": {
            "key2": "value",
            "key3": "value",
            "key4": {}
        },
        "key5": "value"
    }
}]

我想将数据结构中所有节点的绝对路径作为数组获取:

[
    "data[0]['key1']['children'][0]['key2']", 
    "data[0]['key1']['children'][0]['key3']", 
    "data[0]['key1']['children'][0]['key4']", 
    ......, 
    "data[0]['key1']['children'][1]['key2']",
    ......., 
    "data[1]['key1']['children']['key2']",
    ..........
]

有没有办法在 JS 中完成这项工作?

4

2 回答 2

5

我编写了一个自定义代码,它为我们提供了所有节点的 JSON 路径作为数组

function toArray(obj, name) {
    var result = [];
    var passName;
    var tempArray = [];
    for (var prop in obj) {
        var value = obj[prop];
        if (typeof value === 'object') {
            if ($.isNumeric(prop)) {
                passName = name + "[" + prop + "]";
            } else {
                passName = name + "['" + prop + "']";
            }
            tempArray = toArray(value, passName);
            $.each(tempArray, function (key, value) {
                result.push(value);
            });

        } else {
            result.push(name + "['" + prop + "']");
        }
    }
    return result;
}

JS小提琴

于 2013-09-05T08:00:17.617 回答
2

好吧,我认为您必须遍历整个 json 结构..

  for(var i=0; i<data.length; i++) {
     for(var j in data[i]){
       //and so on
      }
   }

或者简单地说,您可以为每个键创建 aleas 数组,其中键将是该值的路径,并以“_”作为分隔符,如..

 var aleasArray = []; 
 for(var i=0; i<data.length; i++) {
     for(var j in data[i]){
      aleasArray[i + '_' + j] = data[i][j];  // if you want make it more generalize aleas array..
      }
   }

希望对你有帮助..

于 2013-09-05T07:10:20.657 回答