json 在golang中将地图转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48149969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:04:46  来源:igfitidea点击:

Converting map to string in golang

jsongonomad

提问by ecl0

I am trying to find the best way to convert

我试图找到最好的转换方式

map[string]stringto 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-variableshttps://github.com/hashicorp/nomad/blob/master/nomad/structs/structs.go#L3647

map[string]string输入字符串。我尝试使用 marshall 转换为 json 以保持格式,然后转换回字符串,但这没有成功。更具体地说,我试图将包含键和 val 的映射转换为字符串以适应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",
    }

回答by Shaban Naasso

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

PS你刚刚更新了你的问题,我看到你仍然需要在值周围引用,所以这里是引用

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

工作示例: 去游乐场

回答by Peter Gloor

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

您可以在The Go Playground 中看到这一点