Home > Backend Development > Golang > How to Handle JSON String to Float64 Conversion in Go?

How to Handle JSON String to Float64 Conversion in Go?

Susan Sarandon
Release: 2025-01-04 21:22:43
Original
858 people have browsed it

How to Handle JSON String to Float64 Conversion in Go?

Decoding JSON with Float64 Type Conversion

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"`
}
Copy after login

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)
    }
}
Copy after login

Running this updated code will now output the desired result:

{Name:Galaxy Nexus Price:3460}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template