Stop json.Marshal() from stripping trailing zero from floating point number

后端 未结 5 525
梦谈多话
梦谈多话 2020-12-21 01:04

I got the following problem: My golang program converts some information into JSON. For example it results in the following json:

{
   \"value\":40,
   \"uni         


        
5条回答
  •  忘掉有多难
    2020-12-21 01:12

    I had a similar issue where I wanted to marshal a map[string]interface{} with float values f.x 1.0 to JSON as 1.0. I solved it by adding a custom Marshal function for a custom float type and then replace the floats in the map with the custom type:

    type customFloat float64
    
    func (f customFloat) MarshalJSON() ([]byte, error) {
        if float64(f) == math.Trunc(float64(f)) {
            return []byte(fmt.Sprintf("%.1f", f)), nil
        }
        return json.Marshal(float64(f))
    }
    
    func replaceFloat(value map[string]interface{}) {
        for k, v := range value {
            switch val := v.(type) {
            case map[string]interface{}:
                replaceFloat(val)
            case float64:
                value[k] = customFloat(val)
            }
        }
    }
    

    Then replace all float64 nodes:

    replaceFloat(myValue)
    bytes, err := json.Marshal(myValue)
    

    This will print the floats like 1.0

提交回复
热议问题