[英]How to decode JSON with type convert from string to float64
我需要使用浮点数解码 JSON 字符串,例如:
{"name":"Galaxy Nexus", "price":"3460.00"}
我使用下面的 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)
}
}
当我运行它时,得到结果:
json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
我想知道如何使用类型转换解码 JSON 字符串。
答案要简单得多。 只需添加告诉 JSON 解释器它是一个用,string
string 编码的 float64 字符串(请注意,我只更改了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)
}
}
只是让您知道您可以在没有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)
}
避免将字符串转换为 []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)
}
}
在引号中传递一个值会使它看起来像字符串。 将"price":"3460.00"
更改为"price":3460.00
,一切正常。
如果你不能删除引号,你必须自己解析它,使用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\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", pro)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.