Home > Backend Development > Golang > How to Decode JSON Strings with Float64 Values Stored as Strings in Go?

How to Decode JSON Strings with Float64 Values Stored as Strings in Go?

Linda Hamilton
Release: 2025-01-01 12:59:11
Original
198 people have browsed it

How to Decode JSON Strings with Float64 Values Stored as Strings in Go?

Decoding JSON with Type Conversion from String to float64 in Go

Parsing JSON strings that contain float64 values can pose challenges when the values are stored as strings. To address this issue, Go provides a straightforward solution.

Understanding the Error:

When attempting to decode a JSON string like "{"name":"Galaxy Nexus", "price":"3460.00"}" using the json.Unmarshal function, you might encounter the following error:

json: cannot unmarshal string into Go value of type float64
Copy after login

This error occurs because the JSON decoder tries to convert the string representation of the float64 number to a float64 value directly, which is not supported.

Solution: Type Conversion Annotation

To resolve this issue, you need to explicitly instruct the decoder to treat the string as a float64 using a type conversion annotation. This annotation is added to the field definition in the Product struct:

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

The ",string" tag tells the JSON decoder that the Price field is a string that should be converted to a float64.

Updated Code:

Here's the updated Go 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

Expected Output:

Running this code will produce the expected output:

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

The json.Unmarshal function successfully decoded the JSON string and converted the price from a string to a float64.

The above is the detailed content of How to Decode JSON Strings with Float64 Values Stored as Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!

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