Partly JSON unmarshal into a map in Go

前端 未结 3 1835
一向
一向 2020-11-29 15:34

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, te

3条回答
  •  感动是毒
    2020-11-29 16:15

    This can be accomplished by Unmarshaling into a 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-

提交回复
热议问题