Skip to content

Instantly share code, notes, and snippets.

@patik
Created June 18, 2014 16:01
Show Gist options
  • Save patik/13b3a196c9b770d40898 to your computer and use it in GitHub Desktop.
Save patik/13b3a196c9b770d40898 to your computer and use it in GitHub Desktop.
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