Skip to content

Instantly share code, notes, and snippets.

@jazzedge
Created July 27, 2017 04:48
Show Gist options
  • Select an option

  • Save jazzedge/477176847ba6f51242634d66e40134da to your computer and use it in GitHub Desktop.

Select an option

Save jazzedge/477176847ba6f51242634d66e40134da to your computer and use it in GitHub Desktop.
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);
}
// ----------------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment