在golang中将地图转换为字符串 [英] Converting map to string in golang

查看:143
本文介绍了在golang中将地图转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找转换的最佳方法

map[string]string键入string.我尝试使用marshall转换为json以保留格式,然后转换回字符串,但这未成功.更具体地说,我正在尝试将包含键和值的映射转换为字符串以容纳

地图

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

我了解您需要在代表一个地图条目的每一行上使用一些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))

}

工作示例: 去游乐场

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

解决方案

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

这篇关于在golang中将地图转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆