In Golang, parsing JSON integer values as floats is a common problem. The default encoding/json package does not distinguish between integer and float numbers, leading to data type conflicts and write failures when interacting with databases. To address this issue, we can employ alternative approaches for parsing JSON values.
One solution is to utilize the general Go mechanism for custom JSON values. By implementing a custom JSON type that differentiates between integers and floats, we can control the data type conversion process. An example implementation is shown below:
type MyInt int64 func (mi MyInt) MarshalJSON() ([]byte, error) { return []byte(strconv.FormatInt(int64(mi), 10)), nil }
This custom type converts integer values to strings when marshaling them into JSON. To unmarshal JSON values into custom types, we can use a json.Unmarshal function:
var raw map[string]interface{} err := json.Unmarshal([]byte(str), &raw) parsed := make(map[string]interface{}, len(raw)) for key, val := range raw { s := string(val) i, err := strconv.ParseInt(s, 10, 64) if err == nil { parsed[key] = MyInt(i) continue } // Handle other types as needed }
Another approach involves the use of json.Number, a type that represents JSON numbers. It provides methods for converting the number to int64 and float64 values, allowing us to manually handle the type conversion:
var parsed map[string]interface{} d := json.NewDecoder(strings.NewReader(str)) d.UseNumber() err := d.Decode(&parsed) for key, val := range parsed { n, ok := val.(json.Number) if !ok { continue } if i, err := n.Int64(); err == nil { parsed[key] = i continue } if f, err := n.Float64(); err == nil { parsed[key] = f continue } }
The above is the detailed content of How Can I Parse JSON Integers as Integers, Not Floats, in Golang?. For more information, please follow other related articles on the PHP Chinese website!