I have JSON key which will have any one the below data.
1.{"value": "ve"}
2.{"value": ["ve","ff"]}
3.{"value": [1,2]}
4.{"value": 3}
How to unmarshal into a golang's struct?
I have JSON key which will have any one the below data.
1.{"value": "ve"}
2.{"value": ["ve","ff"]}
3.{"value": [1,2]}
4.{"value": 3}
How to unmarshal into a golang's struct?
The easiest way is to just use interface{} in your struct. See:
package main
import (
"encoding/json"
"fmt"
)
type decoded struct {
Value interface{} `json:"value"`
}
func decode(jstr string) {
var val decoded
json.Unmarshal([]byte(jstr), &val)
fmt.Printf("%v
", val.Value)
}
func main() {
decode(`{"value": "ve"}`)
decode(`{"value": ["ve","ff"]}`)
decode(`{"value": [1,2]}`)
decode(`{"value": 3}`)
}
You'll probably need to combine this with stuff in the reflect package or (as I did above) fmt.Sprintf() or similar to actually get at your data. This is, however, good enough to decode and put in a structure:
$ ./spike
ve
[ve ff]
[1 2]
3