dsf12313
2012-02-26 12:05
浏览 285

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

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

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

I use the Golang code below:

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
", pro)
    } else {
        fmt.Println(err)
        fmt.Printf("%+v
", 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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • duanchun1852 2012-03-05 21:01
    已采纳

    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 Price definition):

    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
    ", pro)
        } else {
            fmt.Println(err)
            fmt.Printf("%+v
    ", pro)
        }
    }
    
    点赞 打赏 评论
  • duancenxie2233 2012-02-26 12:45

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

    If you can't drop the quotations marks you have to parse it by yourself, using 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
    ", pro)
        } else {
            fmt.Println(err)
            fmt.Printf("%+v
    ", pro)
        }
    }
    
    点赞 打赏 评论
  • dongshou6788 2015-11-19 07:38

    Just letting you know that you can do this without Unmarshal and use json.decode. Here is 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)
    }
    
    点赞 打赏 评论
  • dougua2309 2018-10-23 07:11

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

    strings.NewReader interface is better. Below is the code from 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
    ", m.Name, m.Text)
        }
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题