How to Convert JSON to Map in Golang

To convert a json to a map in Go, use the “json.Unmarshal()” function and pass the JSON string as “bytearray” and the “address of an empty map” as arguments to the function.

The json.Unmarshal() method parses the JSON-encoded data and stores the result in the value pointed to by the interface. If an interface is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

package main

import (
  "encoding/json"
  "fmt"
  "reflect"
)

func main() {
 // Simple Employee JSON object which we will parse
  coronaVirusJSON := `{
    "name" : "covid-11",
    "country" : "China",
    "city" : "Wuhan",
    "reason" : "Non vedge Food"
  }`

 // Declared an empty map interface
 var result map[string]interface{}

 // Unmarshal or Decode the JSON to the interface.
 json.Unmarshal([]byte(coronaVirusJSON), &result)

 // Print the data type of result variable
 fmt.Println(reflect.TypeOf(result))

 // Reading each value by its key
 fmt.Println("Name :", result["name"],
 "\nCountry :", result["country"],
 "\nCity :", result["city"],
 "\nReason :", result["reason"])
}

Output

map[string]interface {}
Name : covid-11
Country : China
City : Wuhan
Reason : Non vedge Food

That’s it.

1 thought on “How to Convert JSON to Map in Golang”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.