jeudi 7 mai 2015

Golang JSON array of different types reflection: float64 vs int64

Consider this simple example:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "reflect"
)

var args = `[1, 2.5, "aaa", true, false]`

func main() {
    var x []interface{}
    err := json.Unmarshal([]byte(args), &x)

    if err != nil {
        log.Fatalf("%s", err.Error())
        panic(fmt.Sprintf("%s", err.Error()))
    }

    for _, arg := range x {
        t := reflect.TypeOf(arg).Kind().String()
        v := reflect.ValueOf(arg)

        if t == "int64" {
            fmt.Printf("int64 %v\n", v.Int())
        }

        if t == "float64" {
            fmt.Printf("float64 %v\n", v.Float())
        }

        if t == "string" {
            fmt.Printf("string %v\n", v.String())
        }

        if t == "bool" {
            fmt.Printf("bool %v\n", v.Bool())
        }
    }
}

The program outputs:

float64 1
float64 2.5
string aaa
bool true
bool false

As you can see, my input is a valid JSON which represents an array with five items:

- integer
- floating point number
- string
- boolean
- boolean

When I unmarshal the valid JSON string into []interface{} and try to check the types with reflection, the integer value from JSON has a type of float64. Any idea why? Is this expected behaviour?





Aucun commentaire:

Enregistrer un commentaire