How to Convert JSON to Map in Golang

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

Golang json is one of the most used packages. JSON(JavaScript Object Notation) parsing a day-to-activity for a developer.

Most of the API which developers parse is in JSON. Here we will see how we can parse JSON Object to Map.

We can parse JSON Object and Array using Golang Interfaces. It reduces the overhead of creating a struct when data is unstructured, and we can parse the data and get the desired value from the JSON.

Example

Let’s see the following 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

Explanation

First, we have imported the “encoding/json”, “fmt”, and “reflect” packages.

Then inside the main(), I have defined a specific JSON object called coronaVirusJSON object. It has four properties, and now we need to convert that json object to a map and display its key and value one by one in the console.

In the next step, I have declared a map of the string with an empty interface that will hold the parsed json.

Then I used the json.Unmarshal() function to Unmarshal the json string by converting it byte into the map. Unmarshal parses JSON-encoded data and stores the result in the value pointed to by an interface.

If an interface is a nil or not a pointer, Unmarshal returns an InvalidUnmarshalError. The Unmarshal() function uses the inverse of Marshal’s encodings, allocating maps, slices, and pointers.

In the final step, we printed the value by its key because the result is a map variable, and we can access it through its keys.

That’s it for this tutorial.

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.