Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you get a JSONPath to all child nodes in an array of JSON object?

How would you get a JSONPath to all child node of an object?

E.g.:

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"
    }
}]

I want to get absolute path for all nodes in the data structure as an array:

[
    "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']",
    ..........
]

Is there any way to get this done in JS?

like image 360
Okky Avatar asked Mar 23 '23 13:03

Okky


1 Answers

I wrote a custom code that gives us JSON path of all nodes as array

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 Fiddle

like image 89
Okky Avatar answered Mar 25 '23 03:03

Okky