Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

πŸ—ΊοΈ Convert map to JSON in Go

introduction json strings

Please consider supporting us by disabling your ad blocker

In Go, you can easily convert a map to a JSON string using encoding/json package. It does not matter if the map contains strings, arrays, structures, numerical values, or another map. The only thing you should remember is that JSON allows only string keys, so if you have an integer key in your map, it will be converted to a string.

package main

import (

type color struct {
    Name    string `json:"name"`
    HexCode string `json:"hex_code"`

func main() {
    data := make(map[string]interface{})
    data = map[string]interface{}{
        "best_fruit":      "apple",                                 // string value
        "best_vegetables": []string{"potato", "carrot", "cabbage"}, // array value
        "best_websites": map[int]interface{}{ // map value
            1: "", // integer key, string value
        "best_color": color{
            Name:    "red",
            HexCode: "#FF0000",
        }, // struct value

    jsonBytes, err := json.MarshalIndent(data, "", "   ")
    if err != nil {


json.MarshalIndent produces JSON encoding of the map with indentation. If you need output without indentation, use json.Marshal.


   "best_color": {
      "name": "red",
      "hex_code": "#FF0000"
   "best_fruit": "apple",
   "best_vegetables": [
   "best_websites": {
      "1": ""

πŸ—ƒοΈ 3 ways to pretty print JSON in Go

Learn how to generate JSON with indentation
introduction json strings

πŸ’ Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

πŸ–¨οΈ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice