Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert map[interface {}]interface {} to map[string]string

Tags:

interface

go

map

From a source I cannot influence I am given data in a map, which arrives as map[interface {}]interface {}.

I need to process the contained data, preferably as map[string]string (the data within is perfectly suitable for that).

I need to generate a list of the keys from the data as well, as those are not known beforehand.

Most similar questions I could find on the web say more or less, that this is impossible, but if my map is m, fmt.Println(m) shows the data is there, readable as map[k0:v0 K1:v1 k2:v2 ... ].

How can I do what fmt.Println is able to do?

like image 597
user3160501 Avatar asked Nov 17 '14 15:11

user3160501


People also ask

How to convert interface type to string in golang?

To convert interface to string in Go, use fmt. Sprint function, which gets the default string representation of any value. If you want to format an interface using a non-default format, use fmt. Sprintf with %v verb.

What is MAP string interface Golang?

What is a map[string]interface{} ? If you've read the earlier tutorial in this series on map types, you'll know how to read this code right away. The type of the foods variable in the above example is a map where the keys are strings, and the values are of type interface{} .


1 Answers

A secure way to process unknown interfaces, just use fmt.Sprintf()

https://play.golang.org/p/gOiyD4KpQGz

package main  import (     "fmt" )  func main() {      mapInterface := make(map[interface{}]interface{})        mapString := make(map[string]string)      mapInterface["k1"] = 1     mapInterface[3] = "hello"     mapInterface["world"] = 1.05      for key, value := range mapInterface {         strKey := fmt.Sprintf("%v", key)         strValue := fmt.Sprintf("%v", value)          mapString[strKey] = strValue     }      fmt.Printf("%#v", mapString) } 
like image 170
wakumaku Avatar answered Oct 12 '22 13:10

wakumaku