how to convert json to map in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert json to map in golang, use json.Unmarshal() method with []byte, it will convert json string to map. You have to only pass your json string with byte in json.Unmarshal() method.


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 json to map in golang, as above mentioned I’m going to use json.Unmarshal() method.

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

Let’s start our Golang convert json to map example

main.go

package main
 
import (
    "encoding/json"
    "fmt"
)
 
func main() {
    jsonStr := `{"id": 1, "name": "aGuideHub"}`
    var x map[string]interface{}
 
    json.Unmarshal([]byte(jsonStr), &x)
    fmt.Println(x)
}

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

Output

map[id:1 name:aGuideHub]

I hope it helps you, All the best 👍.

Follow me on Twitter