[英]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.