Created
April 22, 2014 23:36
-
-
Save jnevelson/11198017 to your computer and use it in GitHub Desktop.
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
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