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

yan*_*non 73 json go

我需要解码一个带有浮点数的JSON字符串,如:

{"name":"Galaxy Nexus", "price":"3460.00"}
Run Code Online (Sandbox Code Playgroud)

我使用下面的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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用convert类型解码JSON字符串.

Dus*_*tin 146

答案要简单得多.只需添加告诉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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`json:"前面的前导逗号,字符串"`是必要的 - 如果没有它,它将无法工作. (3认同)
  • 有谁知道如何同时接受数字和字符串? (3认同)
  • @dustin知道怎么做吗?将json数字转换为字符串?例如`"N": 1234` 到`N: "1234"`? (2认同)

Sal*_*ali 9

只是让你知道你可以在没有Unmarshal使用的情况下做到这一点json.decode.这是Go Playground

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)
}
Run Code Online (Sandbox Code Playgroud)


g10*_*ang 6

避免将字符串转换为 []byte: 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)
    }
}
Run Code Online (Sandbox Code Playgroud)