23

I am trying to find the best way to convert map[string]string to type string.

I tried converting to JSON with marshalling to keep the format and then converting back to a string, but this was not successful.

More specifically, I am trying to convert a map containing keys and values to a string to accommodate Environment Variables and structs.go.

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",
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ecl0
  • 385
  • 1
  • 3
  • 13
  • 2
    Please include a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Marc Jan 08 '18 at 12:11
  • 1
    Yeah can you explain how should be the final string? – Bestbug Jan 08 '18 at 12:38
  • 1
    You're not showing what you tried, and your description is very vague. From the looks of it, the values are not all strings (eg: `true` is not the same as the string `"true"`). – Marc Jan 08 '18 at 12:52

6 Answers6

26

You need some key=value pair on each line representing one map entry, and you need quotes around the values:

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

}

Here is a working example on Go Playground.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shaban Naasso
  • 307
  • 1
  • 6
  • 3
17

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))
}
Elviss Strazdins
  • 1,404
  • 14
  • 30
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Gloor
  • 917
  • 6
  • 19
3

This could work:

// 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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anum Sheraz
  • 2,383
  • 1
  • 29
  • 54
0

We could convert map to single line using sf.MapToStr function from github.com/wissance/stringFormatter v1.0.1 (https://github.com/Wissance/stringFormatter):

// ...
import (
    sf "github.com/wissance/stringFormatter"
)
// ...
func MyFunc() {
    options := map[string]interface{}{
        "connectTimeout": 1000,
        "useSsl":         true,
        "login":          "sa",
        "password":       "sa",
    }

    str := sf.MapToString(&options, sf.KeyValueWithSemicolonSepFormat, ", ")
    fmt.Println(str)
}
Michael Ushakov
  • 1,639
  • 1
  • 10
  • 18
-1
jsonString, err := json.Marshal(datas) 
fmt.Println(err)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Max Droid
  • 924
  • 9
  • 10