doushu7588 2019-05-14 05:38
浏览 42

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

This demo: 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
", k, v, k, v, k, v)
    }
}

Output:

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

I want code1 to output 10080061 and code2 to output 12.2. How can I do this done.

  • 写回答

1条回答 默认 最新

  • dotj6816 2019-05-14 07:17
    关注

    try this code

    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
    ", k, int(v.(float64)))
                } else {
                    fmt.Printf("%v: %v
    ", k, v)
                }
            default:
                fmt.Printf("%v: %v
    ", k, v)
            }
        }
    }
    

    output

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

    ref

    评论

报告相同问题?