var constants = {
BLOCK_START: '{',
BLOCK_END: '}'
};
function findDeepestLeaveNodes(json) {
var maxNesting = getMaxNesting(json);
var currentNestLevel = 0;
var results = [];
var jsonLength = json.length;
for (var currentCharIndex = 0; currentCharIndex < jsonLength; currentCharIndex++) {
var currentChar = json.charAt(currentCharIndex);
//console.log("Nesting level " + currentNestLevel + " at character '" + currentChar + "'");
if (currentChar == constants.BLOCK_START) {
// FIXME The following parsing is fairly fragile. It doesn't handle the possibility
// that a '}' or ',' way occur inside a String and therefore do always close a block or
// separate sibling JSON properties. To handle this we'd need to write a proper JSON parser.
if (++currentNestLevel == maxNesting) {
// read the content of the current block
var blockEndIndex = json.indexOf(constants.BLOCK_END, currentCharIndex);
var currentBlock = json.substring(currentCharIndex + 1, blockEndIndex);
// Each position in the properties array will contain a property name and it's value
var properties = currentBlock.split(',');
for (var i = 0; i < properties.length; i++) {
// parse out the property name
var property = properties[i];
var separatorPosition = properties[i].indexOf(':');
var propertyName = property.substring(0, separatorPosition);
results.push(propertyName.trim());
}
}
} else if (currentChar == constants.BLOCK_END) {
--currentNestLevel;
}
}
return results;
}
function getMaxNesting(json) {
var jsonlength = json.length;
var currentNestLevel = 0;
var maxNestLevel = 0;
for (var i = 0; i < jsonlength; i++) {
var currentChar = json.charAt(i);
if (currentChar == constants.BLOCK_START) {
++currentNestLevel;
} else if (currentChar == constants.BLOCK_END) {
// update maxNestLevel if necessary
maxNestLevel = Math.max(currentNestLevel >, maxNestLevel ? currentNestLevel : maxNestLevel;);
--currentNestLevel;
}
}
return maxNestLevel;
}