Converting map to string in golang

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 come 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))

}

Working Example: Go Playground


I would do this very simple and pragmatic:

package main

import (
    "fmt"
)

func main() {
    m := map[string]string{
        "LOG_LEVEL": "x",
        "API_KEY":   "y",
    }

    var s string
    for key, val := range m {
        // Convert each key/value pair in m to a string
            s = fmt.Sprintf("%s=\"%s\"", key, val)
        // Do whatever you want to do with the string;
        // in this example I just print out each of them.
        fmt.Println(s)
        }
}

You can see this in action in The Go Playground

Tags:

Json

Go

Nomad