how to convert map to struct in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert map to struct in golang,

  1. First convert it JSON using json.Marshal() method
  2. Then convert JSON string to struct using json.Unmarshal() method

it will convert map to struct. just you have to covert to MAP to JSON and then JSON to struct.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows


Today, I will show you how do I convert a map to struct in golang, as above mentioned I’m going to use json.Marshal() and json.Unmarshal() method.

To use the json.Marshal() and json.Unmarshal() method, we have first import "encoding/json" package, then we have to create struct variable which we will use to assign value.

Let’s start our Golang convert map to struct example

main.go

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // map data
    mapData := map[string]interface{}{
        "Name": "noknow",
        "Age": 2,
        "Admin": true,
        "Hobbies": []string{"IT","Travel"},
        "Address": map[string]interface{}{
            "PostalCode": 1111,
            "Country": "Japan",
        },
        "Null": nil,
    }

    // struct - Need to be defined according to the above map data.
    type Addr struct {
        PostalCode int
        Country string
    }
    type Me struct {
        Name string
        Age int
        Admin bool
        Hobbies []string
        Address Addr
        Null interface{}
    }

    // Convert map to json string
    jsonStr, err := json.Marshal(mapData)
    if err != nil {
        fmt.Println(err)
    }

    // Convert json string to struct
    var me Me
    if err := json.Unmarshal(jsonStr, &me); err != nil {
        fmt.Println(err)
    }

    // Output
    fmt.Println(me)
}

In the above example, we have converted the map to struct and printed in golang console. let’s check the output.

Output

{noknow 2 true [IT Travel] {1111 Japan} <nil>}

I hope it helps you, All the best 👍.

Follow me on Twitter