Skip to content

Instantly share code, notes, and snippets.

@pxlpnk
Created September 1, 2019 05:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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