snippetgoCritical
How to decode JSON with type convert from string to float64
Viewed 0 times
withhowfromdecodefloat64convertstringtypejson
Problem
I need to decode a JSON string with the float number like:
I use the Golang code below:
When I run it, get the result:
I want to know how to decode the JSON string with type convert.
{"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\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}I want to know how to decode the JSON string with type convert.
Solution
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)
}
}Code Snippets
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)
}
}Context
Stack Overflow Q#9452897, score: 236
Revisions (0)
No revisions yet.