将interface{}转换为map。

huangapple go评论111阅读模式
英文:

Convert interface{} to map

问题

我正在尝试读取一个 JSON 文件,代码如下:

  1. var configurations map[string]interface{}
  2. func GetConfigMap(name string) interface{} {
  3. valueMap := configurations[name]
  4. return valueMap.(map[string]interface{})
  5. }

我尝试按以下方式读取 map:

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

JSON 结构如下:

  1. {
  2. "glossary": {
  3. "title": "example glossary",
  4. "GlossDiv": {
  5. "title": "S",
  6. "GlossList": {
  7. "GlossEntry": {
  8. "ID": "SGML",
  9. "SortAs": "SGML",
  10. "GlossTerm": "Standard Generalized Markup Language",
  11. "Acronym": "SGML",
  12. "Abbrev": "ISO 8879:1986",
  13. "GlossDef": {
  14. "para": "A meta-markup language, used to create markup languages such as DocBook.",
  15. "GlossSeeAlso": ["GML", "XML"]
  16. },
  17. "GlossSee": "markup"
  18. }
  19. }
  20. }
  21. }
  22. }

我得到了一个异常,提示说:

  1. 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

  1. var configurations map[string]interface{}
  2. func GetConfigMap(name string) interface{} {
  3. valueMap := configurations[name]
  4. return valueMap.(map[string]interface{})
  5. }

And I am trying to read the map as below,

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

The json structure is as below,

  1. { "glossary": {
  2. "title": "example glossary",
  3. "GlossDiv": {
  4. "title": "S",
  5. "GlossList": {
  6. "GlossEntry": {
  7. "ID": "SGML",
  8. "SortAs": "SGML",
  9. "GlossTerm": "Standard Generalized Markup Language",
  10. "Acronym": "SGML",
  11. "Abbrev": "ISO 8879:1986",
  12. "GlossDef": {
  13. "para": "A meta-markup language, used to create markup languages such as DocBook.",
  14. "GlossSeeAlso": ["GML", "XML"]
  15. },
  16. "GlossSee": "markup"
  17. }
  18. }
  19. }
  20. }
  21. }

I am getting an exception that says -

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

How do I make this work?

答案1

得分: 2

根据你的问题,我不确定你想要做什么,但是你可以改变函数的返回类型,不是吗?

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

你可以将函数的返回类型改为 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?

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

huangapple
  • 本文由 发表于 2014年11月20日 11:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/27031129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定