I have a Json:
{
"id": "me",
"name": "myname",
"planets": {
"EARTH": 3,
"MARS": 4
}
}
I don't know how to unmarshal planets field into map[string]int, so I'll get access to the elements without unmarshaling them too like in this example: json to map Golang
Here is the code:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Planets struct {
Planet map[string]*json.RawMessage
} `json:"planets"`
}
func main() {
data := `{
"id": "me",
"name": "myname",
"planets": {
"EARTH": 3,
"MARS": 4
}
}`
user := &User{}
err := json.Unmarshal([]byte(data), user)
if err != nil {
fmt.Println("ERROR " + err.Error())
}
fmt.Println(user.ID)
fmt.Println(user.Planets.Planet["EARTH"])
}
fmt.Println(user.Planets.Planet["EARTH"]) - returns
fmt.Println(user.Planets["EARTH"]) - does not support indexing