Convert Map to JSON

To convert Map object to JSON string in Go language, import the package encode/json, call json.Marshall() function and pass the map object as argument to the function. The function returns json string and an error object.

In this tutorial, we will learn how to convert Map object to a JSON string.

Syntax

The syntax to convert Map x to json is

</>
Copy
jsonStr, err := json.Marshal(x)

JSON supports key of string type only. So, if key in Map is of int type, then this key would be transformed to a String in JSON.

Return Values

If there is any error while conversion, err object would be assigned the error.

If there is no error, then err object would be assigned nil and the jsonStr contains the converted JSON string value.

Examples

In the following program, we take a map map1 and convert this map to JSON string.

example.go

</>
Copy
package main

import (
	"encoding/json"
	"fmt"
)

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

	jsonStr, err := json.Marshal(map1)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
	} else {
		fmt.Println(string(jsonStr))
	}
}

Output

{"a":"apple","b":"banana"}

Map with Integer Keys to JSON

If keys in map are integer values, then the resulting JSON string would contain these keys as string values.

example.go

</>
Copy
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	map1 := map[int]string{
		1: "apple",
		2: "banana",
	}

	jsonStr, err := json.Marshal(map1)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
	} else {
		fmt.Println(string(jsonStr))
	}
}

Output

{"1":"apple","2":"banana"}

Nested Map to JSON

In the following program, we will take a nested map in x, and convert this map to JSON String.

example.go

</>
Copy
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var x = map[string]map[string]string{}

	x["fruits"] = map[string]string{}
	x["colors"] = map[string]string{}

	x["fruits"]["a"] = "apple"
	x["fruits"]["b"] = "banana"

	x["colors"]["r"] = "red"
	x["colors"]["b"] = "blue"

	jsonStr, err := json.Marshal(x)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
	} else {
		fmt.Println(string(jsonStr))
	}
}

Output

{"colors":{"b":"blue","r":"red"},"fruits":{"a":"apple","b":"banana"}}

Conclusion

In this Golang Tutorial, we learned how to convert a Map into JSON string, with the help of example programs.