本文介绍了如何解码JSON的类型从字符串转换为Golang中的float64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用浮点数来解码JSON字符串,例如:
I need to decode a JSON string with the float number like:
{"name":"Galaxy Nexus", "price":"3460.00"}
我使用下面的Golang代码:
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\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}
我想知道如何解码带有类型的JSON字符串C onvert。
I want to know how to decode the JSON string with type convert.
推荐答案
答案相当简单。只需添加告诉JSON中断它是一个字符串编码的float64与,字符串
(请注意,我只更改了 Price
定义) :
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\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", pro)
}
}
这篇关于如何解码JSON的类型从字符串转换为Golang中的float64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!