为了账号安全,请及时绑定邮箱和手机立即绑定

如何解码类型从字符串转换为float64的JSON

如何解码类型从字符串转换为float64的JSON

Go
紫衣仙女 2021-05-03 17:15:39
我需要使用浮点数对JSON字符串进行解码,例如:{"name":"Galaxy Nexus", "price":"3460.00"}我使用下面的Golang代码:package mainimport (    "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)    }}当我运行它时,得到的结果是:json: cannot unmarshal string into Go value of type float64{Name:Galaxy Nexus Price:0}我想知道如何使用convert类型解码JSON字符串。
查看完整描述

3 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

只是让您知道可以不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)

}


查看完整回答
反对 回复 2021-05-10
?
开满天机

TA贡献1786条经验 获得超12个赞

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


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)

    }

}


查看完整回答
反对 回复 2021-05-10
  • 3 回答
  • 0 关注
  • 255 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信