Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created July 29, 2015 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/c647c5cf25c2e08a8097 to your computer and use it in GitHub Desktop.
Save mdwhatcott/c647c5cf25c2e08a8097 to your computer and use it in GitHub Desktop.
Recursively find a value in a JSON object that can contain fields and values, as long as all values are only JSON objects with similarly defined objects with fields and values.
// traverse recursively finds a value in a JSON object that can contain fields and values,
// as long as all values are only JSON objects with similarly defined objects with fields and values.
// This works with structures like the US and International Street APIs.
// example: traverse(d, "components", "primary_number) // will return the primary number of the candidate)
func traverse(i interface{}, keys ...string) interface{} {
var (
found bool
object map[string]interface{}
)
object, found = i.(map[string]interface{})
if !found {
return nil
}
for x, key := range keys {
if x < len(keys)-1 {
object, found = object[key].(map[string]interface{})
if !found {
return nil
}
} else {
i, found = object[key]
if found {
return i
}
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment