Home >Backend Development >Golang >How Can I Partially Unmarshal JSON into a Go Map?
In Go, it's possible to partially unmarshal JSON data into a map when the data is wrapped in an object with key-value pairs. This allows for easy identification of the type of value each key holds.
To achieve this, use the encoding/json package and unmarshal into a map[string]json.RawMessage. The json.RawMessage type captures the underlying JSON data before further parsing.
var objmap map[string]json.RawMessage err := json.Unmarshal(data, &objmap)
Once the map is obtained, you can proceed to parse the value of each key according to its known type.
For the example JSON:
{ "sendMsg":{"user":"ANisus","msg":"Trying to send a message"}, "say":"Hello" }
You can parse sendMsg and say as follows:
type sendMsg struct { User string Msg string } var s sendMsg err = json.Unmarshal(objmap["sendMsg"], &s) var str string err = json.Unmarshal(objmap["say"], &str)
Note that the variables in the sendMsg struct must be exported (i.e., capitalized) for proper unmarshaling, as shown:
type sendMsg struct { User string Msg string }
See a working example here: https://play.golang.org/p/OrIjvqIsi4-
The above is the detailed content of How Can I Partially Unmarshal JSON into a Go Map?. For more information, please follow other related articles on the PHP Chinese website!