Javascript/JSON get path to given subnode?

后端 未结 4 1678
迷失自我
迷失自我 2020-12-03 17:29

How would you get a JSON path to a given child node of an object?

E.g.:

var data = {
    key1: {
        children: {
            key2:\'value\',
             


        
4条回答
  •  感动是毒
    2020-12-03 18:17

    This is the way i have done this.

    /**
     * Converts a string path to a value that is existing in a json object.
     * 
     * @param {Object} jsonData Json data to use for searching the value.
     * @param {Object} path the path to use to find the value.
     * @returns {valueOfThePath|undefined}
     */
    function jsonPathToValue(jsonData, path) {
        if (!(jsonData instanceof Object) || typeof (path) === "undefined") {
            throw "Not valid argument:jsonData:" + jsonData + ", path:" + path;
        }
        path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
        path = path.replace(/^\./, ''); // strip a leading dot
        var pathArray = path.split('.');
        for (var i = 0, n = pathArray.length; i < n; ++i) {
            var key = pathArray[i];
            if (key in jsonData) {
                if (jsonData[key] !== null) {
                    jsonData = jsonData[key];
                } else {
                    return null;
                }
            } else {
                return key;
            }
        }
        return jsonData;
    }  
    

    For testing,

    var obj = {d1:{d2:"a",d3:{d4:"b",d5:{d6:"c"}}}};
    jsonPathToValue(obj, "d1.d2"); // a 
    jsonPathToValue(obj, "d1.d3"); // {d4: "b", d5: Object}
    jsonPathToValue(obj, "d1.d3.d4"); // b
    jsonPathToValue(obj, "d1.d3.d5"); // {d6: "c"}
    jsonPathToValue(obj, "d1.d3.d5.d6"); // c
    

    Hope that will help someone.

提交回复
热议问题