Skip to content

Instantly share code, notes, and snippets.

@bom-d-van
Forked from StarpTech/getJSONVal.go
Created March 11, 2013 00:22
Show Gist options
  • Save bom-d-van/5131141 to your computer and use it in GitHub Desktop.
Save bom-d-van/5131141 to your computer and use it in GitHub Desktop.
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