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

41,909

Solution 1

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

Solution 2

Perhaps I misunderstand the question, but would this work?

m := make(map[interface{}]interface{})
m["foo"] = "bar"

m2 := make(map[string]string)   

for key, value := range m {        
    switch key := key.(type) {
    case string:
        switch value := value.(type) {
        case string:
            m2[key] = value
        }
    }
}
Share:
41,909
user3160501
Author by

user3160501

Updated on January 13, 2020

Comments

  • user3160501
    user3160501 over 4 years

    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?

  • JimB
    JimB over 9 years
    FYI, you can assign in a switch statement, so you don't have to don't have to so the type assertion: play.golang.org/p/-ZeUXTKu9a
  • Swagdaddymuffin
    Swagdaddymuffin over 9 years
    Right, must have missed that in my rush to answer. Thanks!
  • user3160501
    user3160501 over 9 years
    Thank you! This is what i tried initially, but failed. Your example does work, while "my" map refuses to range due to type interface {}. Both are reported as "map[interface {}]interface {}" by reflect.TypeOf but behave differently....????
  • JimB
    JimB over 9 years
    @user3160501: You're probably further obscuring the issue by passing map[interface{}]interface{} as an interface{}. Sounds like you need another type assertion in there, but you need to show an example if you want help.
  • user3160501
    user3160501 over 9 years
    @JimB: sounds like you are pointing in a well helpful direction, although i cannot yet either find where in my code this does happen, nor how i can wrap up a good example. But i will try the latter!
  • Arnie97
    Arnie97 almost 5 years
    The input in this question is map[interface{}]interface{}, not map[string]interface{}.