在golang中将map转换为字符串

时间:2018-01-08 12:06:24

标签: json go nomad

我正在努力寻找转换的最佳方式

map[string]string输入字符串。我尝试用马歇尔转换为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

例如,最终字符串应该像

LOG_LEVEL="x"
API_KEY="y"    

地图

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

5 个答案:

答案 0 :(得分:3)

我知道你需要在代表一个地图条目的每一行上使用一些key = value对。

P.S。你刚刚更新了你的问题,我发现你仍然需要围绕值的引号,所以这里有引号

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

}

工作示例: Go Playground

答案 1 :(得分:2)

您可以使用 def getPlayerData(player): r = requests.get("http://srv.earthpol.com/api/json/residents.php?name=" + player) j = r.json() player = player.lower() global emptyresult emptyresult = False if str(j) == "{}": emptyresult = True else: result = {"town": j[player]["town"], "town-rank": j[player]["townRank"], "nation-ranks": j[player]["nationRanks"], "lastOnline:": j[player]["lastOnline"], "registered": j[player]["registered"], "town-title": j[player]["title"], "nation-title": j[player]["surname"], "friends": j[player]["friends"], "uuid": j[player]["uuid"], "avatar": "https://crafatar.com/avatars/"+ j[player]["uuid"]} return result 将地图转换为字符串:

fmt.Sprint

import ( "fmt" ) func main() { m := map[string]string{ "a": "b", "c": "d", } log.Println("Map: " + fmt.Sprint(m)) }

fmt.Sprintf

答案 2 :(得分:0)

我会这样做非常简单实用:

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

您可以在The Go Playground

中查看此操作

答案 3 :(得分:0)

jsonString, err := json.Marshal(datas) 
fmt.Println(err)

答案 4 :(得分:0)

这个怎么样?

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