Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created September 19, 2016 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/520db8d77a7911fbcc779f20b6c6fc11 to your computer and use it in GitHub Desktop.
Save hnakamur/520db8d77a7911fbcc779f20b6c6fc11 to your computer and use it in GitHub Desktop.
parse JSON field which may be string or number in Go
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 string
func (s *StringOrNumber) UnmarshalJSON(data []byte) error {
if bytes.HasPrefix(data, []byte{'"'}) {
var str string
err := json.Unmarshal(data, &str)
if err != nil {
return err
}
*s = StringOrNumber(str)
} else {
*s = StringOrNumber(string(data))
}
return nil
}
@hnakamur
Copy link
Author

The result.

$ go run main.go
result[0]: {Name:foo Value:100}
result[1]: {Name:bar Value:200}
result[2]: {Name:baz Value:X300}

The original article: blog.ichiban: How to parse JSON w/ a field which can be string or number in Go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment