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

前端 未结 3 1054
傲寒
傲寒 2020-11-30 11:07

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, prefera

相关标签:
3条回答
  • 2020-11-30 11:16

    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)
    }
    
    0 讨论(0)
  • 2020-11-30 11:39

    // data is map[string]interface{}
    
    form := make(map[string]string)
    
    for k, v := range data {
        form[k] = v.(string)
    }

    0 讨论(0)
  • 2020-11-30 11:42

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题