Home >Backend Development >Golang >How to Handle 'json: cannot unmarshal string into Go value of type float64' Errors When Decoding JSON?

How to Handle 'json: cannot unmarshal string into Go value of type float64' Errors When Decoding JSON?

Barbara Streisand
Barbara StreisandOriginal
2024-12-31 14:15:10630browse

How to Handle

Decoding JSON with Type Conversion from String to Float64

When decoding a JSON string containing a floating-point number, it's possible to encounter the error "json: cannot unmarshal string into Go value of type float64." This issue arises when the JSON decoder attempts to automatically convert the number from a string to a float64 type.

To solve this issue, you can explicitly tell the JSON decoder that the string represents a float64 by using the ",string" tag in the struct definition:

type Product struct {
    Name  string
    Price float64 `json:",string"`
}

By adding this tag, the JSON decoder will treat the "price" field as a string encoded float64, allowing for proper conversion during decoding.

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)
    }
}

With this modification, the program will now successfully decode the JSON string and correctly convert the "price" field to a float64 type.

The above is the detailed content of How to Handle 'json: cannot unmarshal string into Go value of type float64' Errors When Decoding JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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