Skip to content

Instantly share code, notes, and snippets.

@StarpTech
Last active December 14, 2015 05:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save StarpTech/5035924 to your computer and use it in GitHub Desktop.
Save StarpTech/5035924 to your computer and use it in GitHub Desktop.
Get nested JSON value dynamically by tail-recursion and type-assertions
package main
import (
"fmt"
)
func GetStructField(f interface{},path []string) interface{} {
rangeOver := f.( map[string]interface{})
counter := 0
maxLen := len(path)-1
NESTED: //GOTO *Tail Recursion* more performant by reusing the stack frame
for key, value := range rangeOver {
if key == path[counter] {
next,ok := value.( map[string]interface{} )
if ok {
rangeOver = next
counter += 1
goto NESTED
} else {
if key == path[maxLen] {
return value
}
}
}
}
return nil //Key doesnt point to a value but to a map
}
func main() {
var m = map[string]interface{}{
"path": map[string]interface{}{
"test" : "hello",
"to": map[string]interface{}{
"variable": 1,
"some": map[string]interface{}{
"stuff": ":)",
},
},
},
}
value := GetStructField(m, []string{"path", "to", "some","stuff"} )
value2 := GetStructField(m, []string{"path", "to", "variable"} )
value3 := GetStructField(m, []string{"path", "test"} )
fmt.Printf("%v %v %v", value, value2,value3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment