dsf12313 2012-02-26 12:05
浏览 350
已采纳

如何在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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统