patterngoCritical
Partly JSON unmarshal into a map in Go
Viewed 0 times
partlyunmarshalintojsonmap
Problem
My websocket server will receive and unmarshal JSON data. This data will always be wrapped in an object with key/value pairs. The key-string will act as value identifier, telling the Go server what kind of value it is. By knowing what type of value, I can then proceed to JSON unmarshal the value into the correct type of struct.
Each json-object might contain multiple key/value pairs.
Example JSON:
Is there any easy way using the
Thanks for any kind of suggestion/help!
Each json-object might contain multiple key/value pairs.
Example JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}Is there any easy way using the
"encoding/json" package to do this?package main
import (
"encoding/json"
"fmt"
)
// the struct for the value of a "sendMsg"-command
type sendMsg struct {
user string
msg string
}
// The type for the value of a "say"-command
type say string
func main(){
data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)
// This won't work because json.MapObject([]byte) doesn't exist
objmap, err := json.MapObject(data)
// This is what I wish the objmap to contain
//var objmap = map[string][]byte {
// "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
// "say": []byte(`"hello"`),
//}
fmt.Printf("%v", objmap)
}Thanks for any kind of suggestion/help!
Solution
This can be accomplished by Unmarshaling into a
To further parse
For
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
Example: https://play.golang.org/p/OrIjvqIsi4-
map[string]json.RawMessage.var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)To further parse
sendMsg, you could then do something like:var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)For
say, you can do the same thing and unmarshal into a string:var str string
err = json.Unmarshal(objmap["say"], &str)EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}Example: https://play.golang.org/p/OrIjvqIsi4-
Code Snippets
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)var str string
err = json.Unmarshal(objmap["say"], &str)type sendMsg struct {
User string
Msg string
}Context
Stack Overflow Q#11066946, score: 278
Revisions (0)
No revisions yet.