【问题标题】:Convert interface{} to map将 interface{} 转换为映射
【发布时间】:2015-01-17 19:32:46
【问题描述】:

我正在尝试读取一个 json 文件,执行该操作的代码如下所示

var configurations map[string]interface{}

func GetConfigMap(name string) interface{} {
    valueMap := configurations[name]
    return valueMap.(map[string]interface{})
}

我正在尝试阅读如下地图,

glossary := jsonreader.GetConfigMap("glossary")
fmt.Println(glossary["GlossDiv"])

json结构如下,

{    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

我得到一个例外,上面写着 -

invalid operation: glossary["GlossDiv"] (type interface {} does not support indexing)

我该如何进行这项工作?

【问题讨论】:

    标签: json map interface go


    【解决方案1】:

    根据您的问题,我不确定您要做什么,但是您不能只更改函数的返回类型吗?

    func GetConfigMap(name string) map[string]interface{} {
        valueMap := configurations[name]
        return valueMap.(map[string]interface{})
    }
    

    【讨论】:

    • 您可以在我发布的示例中看到,将 GetConfigMap 的返回类型从 interface{} 更改为 map[string]interface{} 将让您为所欲为。
    猜你喜欢
    • 2018-11-10
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多