Easy Way to Convert JSON to Map in Golang

Learn how to convert JSON to a map in Golang using the json.Unmarshal() method. This method takes a JSON string as an argument and returns a map of key-value pairs.

To convert a json to a map in Golang, you can 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.

Example

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.

#go #golang #json

Easy Way to Convert JSON to Map in Golang
273.45 GEEK