0

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\n", 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.

ineva
  • 11

1 Answers1

2

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

output

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

ref

minji
  • 512
  • 4
  • 16