package main
import ( "log" "fmt" "encoding/json" "reflect" )
func main() { b := []byte(`{"name": "tom", "favNum": 6, "interests": ["knives", "computers"], "usernames": {"github": "TomNomNom", "twitter": "@TomNomNom"}}`) var f interface{} err := json.Unmarshal(b, &f) if err != nil { log.Fatal("Failed to parse JSON") }
m := f.(map[string]interface{})
printStruct("", m)
}
func printStruct(prefix string, m map[string]interface{}) { for k, v := range m { switch vv := v.(type) { case string: fmt.Println(prefix, k, "is string", vv) case float64: fmt.Println(prefix, k, "is number", vv) case []interface{}: fmt.Println(prefix, k, "is an array:") for i, u := range vv { fmt.Println(prefix, i, u) } case map[string]interface{}: fmt.Println(prefix, k, "is a map:") printStruct(prefix + " ", vv) default: fmt.Println(prefix, k, "is a type we can't handle", vv) } } }
str2 := `{ "foo": { "baz": [ 1, 2, 3 ] }, "flag": true, "list": [ "one", 2, true, "4", { "key": "value" }, [ 1, true ] ] }`
var y map[string]interface{} json.Unmarshal([]byte(str2), &y)
fmt.Printf("%+v\n", y)
the_list := y["list"].([]interface{}) for n, v := range the_list { fmt.Printf("index:%d value:%v kind:%s type:%s\n", n, v, reflect.TypeOf(v).Kind(), reflect.TypeOf(v)) }
|