Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- ms "github.com/mitchellh/mapstructure"
- )
- type s1 struct {
- Type string `"json:type"`
- Value int `"json:value"`
- }
- type s2 struct {
- Type string `"json:type"`
- Value string `"json:value"`
- }
- func main() {
- raw := []byte(`[{"type": "number", "value": 15}, {"type": "string", "value": "Hello!"}]`)
- var input []map[string]interface{}
- if err := json.Unmarshal(raw, &input); err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println(input)
- for _, r := range input {
- switch t := r["type"]; t {
- case "number":
- var v1 s1
- config := &ms.DecoderConfig{TagName: "json", Result: &v1}
- decoder, _ := ms.NewDecoder(config)
- decoder.Decode(r)
- fmt.Printf("%+v\n", v1)
- case "string":
- var v2 s2
- config := &ms.DecoderConfig{TagName: "json", Result: &v2}
- decoder, _ := ms.NewDecoder(config)
- decoder.Decode(r)
- fmt.Printf("%+v\n", v2)
- }
- }
- }
- // Output:
- // [map[type:number value:15] map[value:Hello! type:string]]
- // {Type:number Value:15}
- // {Type:string Value:Hello!}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement