如何在 Golang 中使用从字符串到 float64 的类型转换来解码 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9452897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:12:09  来源:igfitidea点击:

How to decode JSON with type convert from string to float64 in Golang?

jsongo

提问by yanunon

I need to decode a JSON string with the float number like:

我需要使用浮点数解码 JSON 字符串,例如:

{"name":"Galaxy Nexus", "price":"3460.00"}

I use the Golang code below:

我使用下面的 Golang 代码:

package main

import (
    "encoding/json"
    "fmt"
)

type Product struct {
    Name  string
    Price float64
}

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

When I run it, get the result:

当我运行它时,得到结果:

json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}

I want to know how to decode the JSON string with type convert.

我想知道如何使用类型转换解码 JSON 字符串。

回答by Dustin

The answer is considerably less complicated. Just add tell the JSON interpeter it's a string encoded float64 with ,string(note that I only changed the Pricedefinition):

答案要简单得多。只需添加告诉 JSON interpeter 它是一个用 float64 编码的字符串,string(请注意,我只更改了Price定义):

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

回答by Salvador Dali

Just letting you know that you can do this without Unmarshaland use json.decode. Here is Go Playground

只是让您知道您可以在没有Unmarshal和使用的情况下执行此操作json.decode。这是去游乐场

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

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

func main() {
    s := `{"name":"Galaxy Nexus","price":"3460.00"}`
    var pro Product
    err := json.NewDecoder(strings.NewReader(s)).Decode(&pro)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(pro)
}

回答by Mostafa

Passing a value in quotation marks make that look like string. Change "price":"3460.00"to "price":3460.00and everything works fine.

在引号中传递值使其看起来像字符串。更改"price":"3460.00""price":3460.00,一切正常。

If you can't drop the quotations marks you have to parse it by yourself, using strconv.ParseFloat:

如果你不能去掉引号,你必须自己解析它,使用strconv.ParseFloat

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type Product struct {
    Name       string
    Price      string
    PriceFloat float64
}

func main() {
    s := `{"name":"Galaxy Nexus", "price":"3460.00"}`
    var pro Product
    err := json.Unmarshal([]byte(s), &pro)
    if err == nil {
        pro.PriceFloat, err = strconv.ParseFloat(pro.Price, 64)
        if err != nil { fmt.Println(err) }
        fmt.Printf("%+v\n", pro)
    } else {
        fmt.Println(err)
        fmt.Printf("%+v\n", pro)
    }
}

回答by g10guang

Avoid converting a string to []byte: b := []byte(s). It allocates a new memory space and copy the whole the content into it.

避免将字符串转换为 []byte: b := []byte(s)。它分配一个新的内存空间并将整个内容复制到其中。

strings.NewReaderinterface is better. Below is the code from godoc:

strings.NewReader界面更好。下面是来自 godoc 的代码:

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "strings"
)

func main() {
    const jsonStream = `
    {"Name": "Ed", "Text": "Knock knock."}
    {"Name": "Sam", "Text": "Who's there?"}
    {"Name": "Ed", "Text": "Go fmt."}
    {"Name": "Sam", "Text": "Go fmt who?"}
    {"Name": "Ed", "Text": "Go fmt yourself!"}
`
    type Message struct {
        Name, Text string
    }
    dec := json.NewDecoder(strings.NewReader(jsonStream))
    for {
        var m Message
        if err := dec.Decode(&m); err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s: %s\n", m.Name, m.Text)
    }
}