jazzedge
7/28/2017 - 11:10 AM

Bot - Calculate depth of JSON

Bot - Calculate depth of JSON

// Calculates the maximum depth of a JSON object. You must pass the string before converting it to JSON!
function getDepth(obj) {   //Pass a string, not a JSON obj
    var i = 0;    
    var depth = 0;
    var maxDepth = 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);
}