Skip to main content
  1. Tutorials/

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

·1 min

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 (
    "encoding/json"
    "fmt"
    "log"
)

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: "gosamples.dev", // integer key, string value
        },
        "best_color": color{
            Name:    "red",
            HexCode: "#FF0000",
        }, // struct value
    }

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

    fmt.Println(string(jsonBytes))
}

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

Output:

{
   "best_color": {
      "name": "red",
      "hex_code": "#FF0000"
   },
   "best_fruit": "apple",
   "best_vegetables": [
      "potato",
      "carrot",
      "cabbage"
   ],
   "best_websites": {
      "1": "gosamples.dev"
   }
}