Skip to content

Instantly share code, notes, and snippets.

@ichiban
Last active September 19, 2016 11:44
Show Gist options
  • Save ichiban/c097783b716e971b5f59d2aceecdb778 to your computer and use it in GitHub Desktop.
Save ichiban/c097783b716e971b5f59d2aceecdb778 to your computer and use it in GitHub Desktop.
How to parse JSON w/ a field which can be string or number in Go
[
{
"name" : "foo",
"value" : 100
},
{
"name" : "bar",
"value" : 200
}
]
[
{
"name" : "foo",
"value" : 100
},
{
"name" : "bar",
"value" : 200
},
{
"name" : "baz",
"value" : "X300"
}
]
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := `[
{
"name" : "foo",
"value" : 100
},
{
"name" : "bar",
"value" : 200
}
]`
var nvs []NameValue
if err := json.Unmarshal([]byte(data), &nvs); err != nil {
panic(err)
}
for i := 0; i < len(nvs); i++ {
fmt.Printf("result[%d]: %+v\n", i, nvs[i])
}
}
type NameValue struct{
Name string
Value float64
}
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
data := `[
{
"name" : "foo",
"value" : 100
},
{
"name" : "bar",
"value" : 200
},
{
"name" : "baz",
"value" : "X300"
}
]`
var nvs []NameValue
if err := json.Unmarshal([]byte(data), &nvs); err != nil {
panic(err)
}
for i := 0; i < len(nvs); i++ {
fmt.Printf("result[%d]: %+v\n", i, nvs[i])
}
}
type NameValue struct{
Name string
Value StringOrNumber
}
type StringOrNumber struct{
String string
}
func (s *StringOrNumber) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
var v interface{}
if err := dec.Decode(&v); err != nil {
return err
}
switch v.(type) {
case string:
s.String = v.(string)
case float64:
s.String = fmt.Sprintf("%d", int(v.(float64)))
default:
return fmt.Errorf("unknown type: %+v", v)
}
return nil
}
type NameValue struct{
Name string
Value float64
}
result[0]: {Name:foo Value:100}
result[1]: {Name:bar Value:200}
panic: json: cannot unmarshal string into Go value of type float64
goroutine 1 [running]:
panic(0x124740, 0x10532340)
/usr/local/go/src/runtime/panic.go:500 +0x720
main.main()
/tmp/sandbox440216281/main.go:27 +0x140
result[0]: {Name:foo Value:{String:100}}
result[1]: {Name:bar Value:{String:200}}
result[2]: {Name:baz Value:{String:X300}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment