Skip to content

Instantly share code, notes, and snippets.

@jnevelson
Created April 22, 2014 23:36
Show Gist options
  • Save jnevelson/11198017 to your computer and use it in GitHub Desktop.
Save jnevelson/11198017 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
)
var data = `
{
"a": {
"b": {
"c": {
"d": 5
}
}
}
}
`
func main() {
var response interface{}
if err := json.Unmarshal([]byte(data), &response); err != nil {
log.Fatal(err)
}
val, err := lookup(response, "a", "b", "asdc", "d")
if err != nil {
println(err.Error())
return
}
fmt.Printf("%#v\n", val)
}
func lookup(v interface{}, keys ...string) (interface{}, error) {
switch len(keys) {
case 0:
return v, nil
default:
dict, ok := v.(map[string]interface{})
if !ok {
return nil, errors.New(fmt.Sprintf("%T is not a dictionary", v))
}
return lookup(dict[keys[0]], keys[1:]...)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment