Convert JSON String to Map

To convert JSON String to Map object in Go language, import the package encode/json, call json.Unmarshall() function and pass the JSON String as byte array, and address of an empty map as arguments to the function. The function transforms the JSON string to map, and loads the result at given map address.

In this tutorial, we will learn how to convert or load JSON string into Map object.

Syntax

The syntax to convert JSON string jsonStr to Map object x is

</>
Copy
json.Marshal([]byte[jsonString], &x)

Please notice ampersand symbol as prefix to the second argument. We are giving address of a map object x as second argument.

Examples

There could be different scenarios based on the type of key and value in JSON string, that we would like to convert to map. We discuss some of these scenarios in the following examples.

Type of Key and Value are Known

In the following program, we take a JSON string jsonStr and convert it to Map x. We know that the value of key and value is String. So, we create a Max x with these known constraints.

example.go

</>
Copy
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonStr := `{"a":"apple", "b":"banana"}`
	x := map[string]string{}

	json.Unmarshal([]byte(jsonStr), &x)
	fmt.Println(x)
}

Output

map[a:apple b:banana]

Type of Value is Unknown

If the type of value in key:value pair is unknown while converting JSON string to map object, we specify the type of value as interface.

In the following program, we take a JSON string, with contains nested elements which could transform to a nested map.

example.go

</>
Copy
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	jsonStr := `{
		"fruits" : {
			"a": "apple",
			"b": "banana"
		},
		"colors" : {
			"r": "red",
			"g": "green"
		}
	}`

	var x map[string]interface{}

	json.Unmarshal([]byte(jsonStr), &x)
	fmt.Println(x)
}

Output

map[colors:map[g:green r:red] fruits:map[a:apple b:banana]]

Conclusion

In this Golang Tutorial, we learned how to JSON string into Map object in Go programming, with the help of example programs.