Convert map to JSON in Golang? [4 Methods]


Written by - Deepak Prasad

Different methods in golang to convert map to JSON

In golang there are couple of methods using which we can easily convert map to JSON, some of the methods are:

  1. Using json.Marshal() function
  2. Using json.MarshalIndent() function
  3. Using json.NewEncoder() function
  4. Using jsoniter package

 

Method-1: Using json.Marshal() function

Here is an example where we are using json.Marshal() function to convert the map1 to a JSON encoded byte slice. The returned byte slice is later converted to a string.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// create a map
	map1 := map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
	}

	// convert the map to a JSON encoded byte slice
	jsonContent, err := json.Marshal(map1)
	if err != nil {
		fmt.Println(err)
		return
	}

	// convert the byte slice to a string
	jsonString := string(jsonContent)

	fmt.Println(jsonString) // {"one":1,"three":3,"two":2}
}

 

Method-2: Using json.NewEncoder() function

Another way to convert golang map to JSON is using json.Encoder() function.  This function creates a new encoder that writes to an io.Writer interface. By passing an bytes.Buffer as the io.Writer implementation.

Here's an example of how to use the json.NewEncoder function to convert a Go map to a JSON string:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

func main() {
	// create a map
	map1 := map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
	}

	// create a new buffer
	var buf bytes.Buffer

	// create a new encoder that writes to the buffer
	encoder := json.NewEncoder(&buf)

	// encode the map to the buffer
	err := encoder.Encode(map1)
	if err != nil {
		panic(err)
	}

	// convert the buffer to a string
	jsonString := buf.String()

	fmt.Println(jsonString) // {"one":1,"two":2,"three":3}
}

Here we  can configure the encoder to use a specific indentation or to sort the keys of the json object, by using the SetIndent and SetEscapeHTML methods of the encoder.

 

Method-3: Using json.MarshalIndent() function

This method is similar to the json.Marshal() function, but it formats the JSON output with indentation for better readability.

Here's an example of how to use the json.MarshalIndent() function to convert a map to JSON in Go:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// Define the map
	map1 := map[string]interface{}{
		"name": "Some User",
		"age":  35,
		"address": map[string]string{
			"street": "Random St",
			"city":   "Some town",
			"state":  "Some state",
			"zip":    "12345",
		},
	}

	// Convert the map to JSON
	jsonContent, err := json.MarshalIndent(map1, "", "    ")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Print the JSON data
	fmt.Println(string(jsonContent))
}

In the output you can see that the JSON is having proper indentation:

# go run main.go 
{
    "address": {
        "city": "Some town",
        "state": "Some state",
        "street": "Random St",
        "zip": "12345"
    },
    "age": 35,
    "name": "Some User"
}

 

Method-4: Using jsoniter package

Another way to convert gplang map to JSON is using jsoniter.Marshal() function part jsoniter package from github .

You have to install the package using

go get "github.com/json-iterator/go"

Sample Example:

package main

import (
	"fmt"

	jsoniter "github.com/json-iterator/go"
)

func main() {
	// create a map
	map1 := map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
	}

	// convert the map to a JSON encoded byte slice
	jsonContent, err := jsoniter.Marshal(map1)
	if err != nil {
		fmt.Println(err)
		return
	}

	// convert the byte slice to a string
	jsonString := string(jsonContent)

	fmt.Println(jsonString)
	// Output: {"one":1,"two":2,"three":3}
}

 

Summary

In this tutorial we covered various methods in golang to convert map to JSON using built-in and third party libraries. There are many other libraries which can also be used such as easyjson which we have not covered in this tutorial because of the complexity involved in creating the struct for the JSON.

You can try the examples and let us know if you face any issues.

 

References

Convert Go map to json - Stack Overflow

 

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment