Skip to content

Instantly share code, notes, and snippets.

@patik patik/data.js
Created Jun 18, 2014

Embed
What would you like to do?
Simple JSON path parser
// Source data (JSON) from the server
data = {
abc: {
def: {
ghi: 'jkl'
}
}
};
// The path you're looking for (you want the value of `ghi`)
path = 'abc.def.ghi';
// Break up the path into properties
parts = path.split('.');
// Get the name of the value
// Note that `.pop` will alter the array so `parts` now only contains `['abc', 'def']`
valueName = parts.pop();
// This will hold your value. Start by assigning to the data object as a whole
value = data;
// Loop through `parts` to drill deeper into the data
parts.forEach(function(part) {
// Replace the current property with the next (one level deeper) property
value = value[part];
});
// Now that we've gone through the parts of the path, we're at the last property/object, `def`. The only thing left is to get the value:
value = value[valueName];
// Now `value = 'jkl'`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.