I’m RTFMing, especially the part about decoding arbitrary data. Based on that part, I wrote the following test program
var f interface{} json.Unmarshal( []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`), &f) m := f.(map[string]interface{}) for k, v := range m { switch vv := v.(type) { case string: fmt.Println(k, "is string", vv) case int: fmt.Println(k, "is int", vv) case []interface{}: fmt.Println(k, "is an array:") for i, u := range vv { fmt.Println(i, u) } default: fmt.Println(k, "is of a type I don't know how to handle") fmt.Println("Type Is:", vv) } }
That is, I declare a variable with an empty interface type. According to the documentation, I
Use type assertions to access the underlying mapping of f [string] interface {}:
I then used range
to do a for loop over the key/value pairs of the map. If the value is a string, int or [] interface, the program says this. If the value is another One type (default case), the program says I don’t know what to do with it. This is pretty much dictionary-by-dictionary from the manual.
The program produces the following output.
Name is string Wednesday Age is of a type I don't know how to handle Type Is: 6 Parents is an array: 0 Gomez 1 Morticia
That is – it correctly recognizes the types of strings and arrays – for some reason it seems that the parsed type 6
is not and int
– it is 6.
So – I guess my question is *Why does v.(type)
return an actual number hereor my question is Why is this the wrong question?
1> JimB..:
JSON numbers are double precision floating point numbers, so the default type is go uses float64
.You can see the default values listed in the json.Unmarshal
documentation.