AppDividend
Latest Code Tutorials

How to Convert JSON to Map in Golang

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.

Golang JSON to Map

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.

We can parse JSON Object and Array using Golang Interfaces. It reduces overhead to 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.

// hello.go

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

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

Explanation

First, we have imported “encoding/json”, “fmt”, “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 have 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 nil or not pointer, Unmarshal returns an InvalidUnmarshalError. The Unmarshal() function uses the inverse of the encodings that Marshal uses, allocating maps, slices, and pointers.

In the final step, we have 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 Comment
  1. Nivetha says

    How to write a code to read a json file and then unmarshall and put in struct

Leave A Reply

Your email address will not be published.

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