Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting map to string in golang

Tags:

json

go

nomad

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",
    }
like image 280
ecl0 Avatar asked Jan 08 '18 12:01

ecl0


People also ask

Why is Golang map unordered?

Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.

Is map a type in Golang?

There's no such specific data type in Golang called map; instead, we use the map keyword to create a map with keys of a certain type and values of another type (or the same type).

Is there a map function in Golang?

Map() Function in Golang With Examples. strings. Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function.


2 Answers

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

like image 167
Shaban Naasso Avatar answered Oct 09 '22 10:10

Shaban Naasso


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))
}
like image 34
Elviss Strazdins Avatar answered Oct 09 '22 09:10

Elviss Strazdins