Created
September 19, 2016 12:21
-
-
Save hnakamur/520db8d77a7911fbcc779f20b6c6fc11 to your computer and use it in GitHub Desktop.
parse JSON field which may be string or number in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result.
The original article: blog.ichiban: How to parse JSON w/ a field which can be string or number in Go