12

I am trying to find the best way to convert

map[string]string to type string . I tried converting to json with marshall to keep the format and then converting back to string but this was not successful. More specifically I am trying to convert a map containing keys and vals to a string to accommodate https://www.nomadproject.io/docs/job-specification/template.html#environment-variables https://github.com/hashicorp/nomad/blob/master/nomad/structs/structs.go#L3647

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

5 回答 5

18

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

于 2018-01-08T12:43:53.270 回答
6

You can use fmt.Sprint to convert the map to string:

import (
    "fmt"
)

func main() {
    m := map[string]string{
        "a": "b",
        "c": "d",
    }

    log.Println("Map: " + fmt.Sprint(m))
}

Or fmt.Sprintf:

import (
    "fmt"
)

func main() {
    m := map[string]string{
        "a": "b",
        "c": "d",
    }

    log.Println(fmt.Sprintf("Map: %v", m))
}
于 2020-12-21T17:20:53.057 回答
4

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

于 2018-01-08T15:50:19.063 回答
0
jsonString, err := json.Marshal(datas) 
fmt.Println(err)
于 2021-04-09T13:38:15.043 回答
0

How about this ?

// Marshal the map into a JSON string.
mJson, err := json.Marshal(m)   
if err != nil {
    fmt.Println(err.Error())
    return
}

jsonStr := string(mJson)
fmt.Println("The JSON data is:")
fmt.Println(jsonStr)
于 2021-05-10T15:27:03.633 回答