[Solved] How to unmarshal struct into map in golang [closed]


Here is an example with marshal and unmarshal using your object definition

package main

import (
    "encoding/json"
    "fmt"
)

type MyObject struct {
    ID      string         `json:"id"`
    Name    string         `json:"name"`
    Planets map[string]int `json:"planets"`
}

func main() {
    aa := &MyObject{
        ID:   "123",
        Name: "pepe",
        Planets: map[string]int{
            "EARTH": 3,
            "MARS":  4,
        },
    }
    // Marshal
    out, err := json.Marshal(aa)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(out))

    // Unmarshal
    bb := &MyObject{}
    err = json.Unmarshal(out, bb)
    fmt.Println(bb.ID, bb.Name, bb.Planets)

}

and you can get an element of the map with bb.Planets["EARTH"]

I hope you can find this useful.

solved How to unmarshal struct into map in golang [closed]