Created
September 1, 2019 05:31
-
-
Save pxlpnk/cc8c0a77efcc188ce2f55fd187f5cb88 to your computer and use it in GitHub Desktop.
dynamic json in lists
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 ( | |
"encoding/json" | |
"fmt" | |
"log" | |
) | |
const inputSound = ` | |
{ | |
"type": "sound", | |
"msg": [{ | |
"this": "that", | |
"sound": "stuff" | |
}] | |
}` | |
const inputSound = ` | |
{ | |
"type": "visual", | |
"msg": [{ | |
"this": "that", | |
"visual": "stuff" | |
}] | |
}` | |
type Envelope struct { | |
Type string | |
Msg interface{} | |
} | |
type Sound struct { | |
This string | |
Sound string | |
} | |
type Visual struct { | |
This string | |
Visual string | |
} | |
func main() { | |
var msg json.RawMessage | |
env := Envelope{ | |
Msg: &msg, | |
} | |
if err := json.Unmarshal([]byte(inputSound), &env); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%+v", env) | |
switch env.Type { | |
case "sound": | |
var sound Sound | |
if err := json.Unmarshal(msg, &sound); err != nil { | |
log.Fatal(err) | |
} | |
env.Msg = sound | |
} | |
for _, item := range env.Msg { | |
fmt.Println(item.This) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment