1024programmer Java Go’s .(type) unexpected behavior when unmarshalling JSON

Go’s .(type) unexpected behavior when unmarshalling JSON

I’m RTFMing, especially the part about decoding arbitrary data. Based on that part, I wrote the following test program

var f interface{}

   []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)
         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.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/770716

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top