How to Convert Map to String in Go

To convert a map to string in Go, convert a map to JSON “using json.Marshal() method and then convert JSON to JSON string using the string() method.”

Using json.Marshal() function and string() method

package main

import (
  "encoding/json"
  "fmt"
)

func main() {
  data := map[string]string{
    "firstName": "John",
    "lastName": "Doe",
  }

  jsonData, err := json.Marshal(data)
  if err != nil {
    fmt.Println(err)
    return
  }

  jsonString := string(jsonData)
  fmt.Println(jsonString)
}

Output

{"firstName":"John","lastName":"Doe"}

In this example:

  1. We define a map named data with some key-value pairs.
  2. We use the json.Marshal() function to convert this map to a JSON byte slice (jsonData).
  3. We then convert jsonData to a string (jsonString) and print it.

If you want to represent a map as a series of key=value pairs, with each pair on a new line and values surrounded by quotes, you’ll have to format the string representation of the map manually.

package main

import (
  "fmt"
)

func main() {
  data := map[string]string{
    "firstName": "John",
    "lastName": "Doe",
  }

  var result string
  for key, value := range data {
    result += fmt.Sprintf("%s=\"%s\"\n", key, value)
  }

  fmt.Print(result)
}

Output

firstName="John"
lastName="Doe"

Using fmt.Sprintf() method

The fmt.Sprint() function is used to convert a map to a string, but it won’t provide the exact format you have described (with each key=value pair on a new line and values surrounded by quotes). Instead, fmt.Sprint() will generate a Go-like representation of the map.

package main

import (
  "fmt"
)

func main() {
  data := map[string]string{
    "firstName": "John",
    "lastName": "Doe",
  }

  var result string
  for key, value := range data {
    result += fmt.Sprint(key, "=\"", value, "\"\n")
  }

  fmt.Print(result)
}

Output

firstName="John"
lastName="Doe"

That’s it!

Related posts

Go map to json

Go map to struct

Go struct fields to map string

Go struct to map

Go json to struct

Go struct to json

Go string to json

Leave a Comment