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?
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 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{} .
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With