In this scenario, you have a JSON string containing a float number that needs to be decoded into a Golang struct. The initial attempt at decoding fails due to the mismatch between the incoming string representation of the float number and the float64 type in the struct.
To resolve this, it's necessary to instruct the JSON decoder to interpret the string value as a float64. This can be achieved by adding the ,string tag to the Price field in the struct definition:
type Product struct { Name string Price float64 `json:",string"` }
With this modification, the decoder will successfully convert the string representation into a float64 value. The updated Golang code:
package main import ( "encoding/json" "fmt" ) type Product struct { Name string Price float64 `json:",string"` } func main() { s := `{"name":"Galaxy Nexus", "price":"3460.00"}` var pro Product err := json.Unmarshal([]byte(s), &pro) if err == nil { fmt.Printf("%+v\n", pro) } else { fmt.Println(err) fmt.Printf("%+v\n", pro) } }
Running this updated code will now output the desired result:
{Name:Galaxy Nexus Price:3460}
The above is the detailed content of How to Handle JSON String to Float64 Conversion in Go?. For more information, please follow other related articles on the PHP Chinese website!