g0c00l.g33k
g0c00l.g33k

Reputation: 2618

Convert interface{} to map

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?

Upvotes: 3

Views: 4730

Answers (1)

Logiraptor
Logiraptor

Reputation: 1518

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{})
}

Upvotes: 2

Related Questions