Created
July 29, 2015 21:06
-
-
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.
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
// 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