jazzedge
7/27/2017 - 4:48 AM

Bot - Node JS get max depth of a JSON structure

Bot - Node JS get max depth of a JSON structure

// ----------------------------------------------------------------------------------------------------
// Calculates the maximum depth of a JSON object. You must pass the string before converting it to JSON!
function getDepth(obj) {
    var depth = 0;
    var maxDepth = 0;
    var i = 0;
    while (i < obj.length)
    {
        switch (obj.substr(i,1)) {
            case "{":
                depth++;
                if (depth > maxDepth) {
                    maxDepth = depth;
                }
                break;
            case "}":
                depth--;
                break;
            default:
                break;
        }
        i++;
    }
    console.log ("Maxdepth:" + (maxDepth-1));
    return (maxDepth-1);
}
// ----------------------------------------------------------------------------------------------------