Created
October 28, 2016 20:41
-
-
Save nuria/064b8d54589d71cb9eb7c3cdc29352e4 to your computer and use it in GitHub Desktop.
JSON object parser. Each leaf node of the object will be keyed by a concatenated key made up of all parent keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Parses a Json Object. | |
The object will be traversed, and each leaf node of the object will | |
be keyed by a concatenated key made up of all parent keys. | |
**/ | |
function MetricLogster(reporter) { | |
} | |
function isArray(obj) { | |
return obj.constructor === Object; | |
} | |
function isObject(obj) { | |
return obj.constructor === Array; | |
} | |
// we assume that if it is not another object or array | |
// it is a primitive type | |
// obviously not true in javascript but true for this module usage | |
function isPrimitive(item) { | |
return !isObject(item) && !isArray(item); | |
} | |
/** | |
* Recurses through objectsand flattens them | |
* into a single level dict of key: value pairs. Each | |
* key consists of all of the recursed keys joined by | |
* separator that is hardcoded to be a dot. | |
**/ | |
MetricLogster.prototype.flatten = function (obj) { | |
// assert what we got was actually an object | |
console.assert(isObject(obj) || isArray(obj)); | |
var dict = {}; | |
var dot = '.'; | |
/** | |
**/ | |
function _flatten(obj, dict, keyPrefix) { | |
if (obj === null) { | |
return dict; | |
} | |
// object has -ad minimum - a key, value pair | |
// {'some-key': 'some-value-maybe-another-object'} | |
// decide if object or array | |
for (var name in obj) { | |
if (obj.hasOwnProperty(name)) { | |
var keyName; | |
if (keyPrefix) { | |
keyName = keyPrefix + dot + name; | |
} else { | |
keyName = name; | |
} | |
if (isPrimitive(obj[name])) { | |
dict[keyName] = obj[name]; | |
} else { | |
// continue recursing | |
// TODO assumes objects, need to deal with arrays too | |
_flatten(obj[name], dict, keyName); | |
} | |
} | |
} | |
return dict; | |
} | |
return _flatten(obj, dict, null); | |
}; | |
/************** Mopdule exports ***********************/ | |
var logster = new MetricLogster(); | |
module.exports = function (reporter) { | |
// Return an application singletion | |
logster.setReporter(reporter); | |
return logster; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment