英文:
Convert interface{} to map
问题
我正在尝试读取一个 JSON 文件,代码如下:
var configurations map[string]interface{}
func GetConfigMap(name string) interface{} {
    valueMap := configurations[name]
    return valueMap.(map[string]interface{})
}
我尝试按以下方式读取 map:
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)
我该如何解决这个问题?
英文:
I am trying to read a json file, the code that does that has something like below
var configurations map[string]interface{}
func GetConfigMap(name string) interface{} {
	valueMap := configurations[name]
	return valueMap.(map[string]interface{})
}
And I am trying to read the map as below,
glossary := jsonreader.GetConfigMap("glossary")
fmt.Println(glossary["GlossDiv"])
The json structure is as below,
{    "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"
                }
            }
        }
    }
}
I am getting an exception that says -
invalid operation: glossary["GlossDiv"] (type interface {} does not support indexing)
How do I make this work?
答案1
得分: 2
根据你的问题,我不确定你想要做什么,但是你可以改变函数的返回类型,不是吗?
func GetConfigMap(name string) map[string]interface{} {
    valueMap := configurations[name]
    return valueMap.(map[string]interface{})
}
你可以将函数的返回类型改为 map[string]interface{}。
英文:
I'm not sure what you're trying to do based on your question, but can't you just change the return type of the function?
func GetConfigMap(name string) map[string]interface{} {
    valueMap := configurations[name]
    return valueMap.(map[string]interface{})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论