问题描述
从我无法影响的来源获得地图中的数据,该数据以 map[interface {}]interface {}
的形式到达.
From a source I cannot influence I am given data in a map, which arrives as map[interface {}]interface {}
.
我需要处理包含的数据,最好是 map[string]string
(里面的数据非常适合).
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.
我在网上找到的大多数类似问题或多或少都说这是不可能的,但是如果我的地图是 m
,fmt.Println(m)
显示数据在那里,可读为 map[k0:v0 K1:v1 k2:v2 ... ]
.
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 ... ]
.
我怎样才能做 fmt.Println 能做的事?
How can I do what fmt.Println is able to do?
推荐答案
一种处理未知接口的安全方式,只需使用 fmt.Sprintf()
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)
}
这篇关于将 map[interface {}]interface {} 转换为 map[string]string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!