Home >Backend Development >Golang >How to Parse JSON Numbers as Integers or Floats in Go?
Parsing JSON Integers as Integers in Go
In Go's encoding/json package, all numbers during JSON parsing are interpreted as floats by default. However, to accurately distinguish between integers and floats while parsing JSON data, consider the following approaches:
Example: Using Custom JSON Values
Use json.RawMessage and strconv to parse numbers as ints and floats, while treating other values as is:
package main import ( "encoding/json" "fmt" "strconv" ) func main() { str := `{"a":123,"b":12.3,"c":"123","d":"12.3","e":true}` var raw map[string]json.RawMessage err := json.Unmarshal([]byte(str), &raw) if err != nil { panic(err) } 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] = i continue } f, err := strconv.ParseFloat(s, 64) if err == nil { parsed[key] = f continue } var v interface{} err = json.Unmarshal(val, &v) if err == nil { parsed[key] = v continue } parsed[key] = val } for key, val := range parsed { fmt.Printf("%T: %v %v\n", val, key, val) } }
Example: Using json.Number
Enable the use of the json.Number type for number parsing, which allows for the explicit handling of integer values:
package main import ( "encoding/json" "fmt" "strings" ) func main() { str := `{"a":123,"b":12.3,"c":"123","d":"12.3","e":true}` var parsed map[string]interface{} d := json.NewDecoder(strings.NewReader(str)) d.UseNumber() err := d.Decode(&parsed) if err != nil { panic(err) } 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 } } for key, val := range parsed { fmt.Printf("%T: %v %v\n", val, key, val) } }
Both of these examples successfully parse JSON numbers as integers or floats, as desired.
The above is the detailed content of How to Parse JSON Numbers as Integers or Floats in Go?. For more information, please follow other related articles on the PHP Chinese website!