Skip to content

Instantly share code, notes, and snippets.

@pxlpnk
Created September 1, 2019 05:31
Show Gist options
  • Save pxlpnk/cc8c0a77efcc188ce2f55fd187f5cb88 to your computer and use it in GitHub Desktop.
Save pxlpnk/cc8c0a77efcc188ce2f55fd187f5cb88 to your computer and use it in GitHub Desktop.
dynamic json in lists
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