如何从json的map [string] interface {}格式化int数字而没有指数?

时间:2019-05-14 05:38:40

标签: go

此演示:https://play.golang.org/p/7tpQNlNkHgG

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    jsonStr := `{"code1":10080061,"code2":12.2}`
    data := map[string]interface{}{}
    json.Unmarshal([]byte(jsonStr), &data)
    for k, v := range data {
        fmt.Printf("%v:%v, %v:%f, %v:%.0f\n", k, v, k, v, k, v)
    }
}

输出:

code1:1.0080061e+07, code1:10080061.000000, code1:10080061
code2:12.2, code2:12.200000, code2:12

我希望代码1输出10080061,并希望代码2输出12.2。 我该怎么做。

1 个答案:

答案 0 :(得分:1)

尝试此代码

package main

import (
    "encoding/json"
    "fmt"
)

func isIntegral(val float64) bool {
    return val == float64(int(val))
}

func main() {
    jsonStr := `{"code1":10080061,"code2":12.2, "code3": 123.23123, "code4": "string"}`

    data := map[string]interface{}{}
    _ = json.Unmarshal([]byte(jsonStr), &data)

    for k, v := range data {
        switch v.(type) {
        case float64:
           // check the v is integer or float
            if isIntegral(v.(float64)) {
                // if v is an integer, try to cast
                fmt.Printf("%v: %d\n", k, int(v.(float64)))
            } else {
                fmt.Printf("%v: %v\n", k, v)
            }
        default:
            fmt.Printf("%v: %v\n", k, v)
        }
    }
}

输出

code1: 10080061
code2: 12.2
code3: 123.23123
code4: string

ref