I need to write some JavaScript code that will take a JSON string, parse it, and return the names of the most-deeply nested properties. For example, for this input:
var json =
"{\
foo: {\
bar: 'something',\
baz: {\
jack: 'other',\
},\
bob: {\
bill: 'hello',\
bilbo: 11,\
baggins: {\
fizz: 'buzz'\
finger: 'bang'\
}\
}\
}\
}";
it should return ['fizz', 'finger']
. There are a couple of caveats:
- the parsing must be done "manually"- i.e. I can't use
eval
or a JS library to parse the JSON - the JSON property values are guaranteed to be strings, numbers, or objects, i.e. no arrays
Here's what I've come up with so far. The main function is findDeepestLeaveNodes
. At the moment the code is a bit inefficient as it has to iterate twice over the whole input String. I'd like to improve this if possible, and am also looking for suggestions for improving the code quality.
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;
}
}
return maxNestLevel;
}