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

introduction json strings

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"
   }
}

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

Learn how to generate JSON with indentation
introduction json strings

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

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

πŸ”Ÿ Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool