Converting map to string in Go

Issue

I am trying to find the best way to convert map[string]string to type string.

I tried converting to JSON with marshalling to keep the format and then converting back to a string, but this was not successful.

More specifically, I am trying to convert a map containing keys and values to a string to accommodate Environment Variables and structs.go.

For example, the final string should be like

LOG_LEVEL="x"
API_KEY="y"

The map

m := map[string]string{
        "LOG_LEVEL": "x",
        "API_KEY": "y",
    }

Solution

I understand you need some key=value pair on each line representing one map entry.

P.S.: You just updated your question and I see you still need quotes around the values, so here comes the quotes:

package main

import (
    "bytes"
    "fmt"
)

func createKeyValuePairs(m map[string]string) string {
    b := new(bytes.Buffer)
    for key, value := range m {
        fmt.Fprintf(b, "%s=\"%s\"\n", key, value)
    }
    return b.String()
}
func main() {
    m := map[string]string{
        "LOG_LEVEL": "DEBUG",
        "API_KEY":   "12345678-1234-1234-1234-1234-123456789abc",
    }
    println(createKeyValuePairs(m))

}

Here is a working example on Go Playground.

Answered By – Shaban Naasso

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.