Created
June 18, 2014 16:01
-
-
Save patik/13b3a196c9b770d40898 to your computer and use it in GitHub Desktop.
Simple JSON path parser
This file contains hidden or 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
// 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'; |
This file contains hidden or 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
// 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