invalid operation: type interface {} does not support indexing

Rohit Kumar picture Rohit Kumar · Dec 11, 2017 · Viewed 9.4k times · Source

I'm new to the golang and I have problem while reading the nested JSON response.

var d interface{}
json.NewDecoder(response.Body).Decode(&d)
test :=d["data"].(map[string]interface{})["type"]

response.Body looks like this

{
    "links": {
      "self": "/domains/test.one"
    },
    "data": {
        "type": "domains",
        "id": "test.one",
        "attributes": {
            "product": " Website",
            "package": "Professional",
            "created_at": "2016-08-19T11:37:01Z"
        }
    }
}

The Error I'm getting is this:

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

Answer

icza picture icza · Dec 11, 2017

d is of type interface{}, so you cannot index it like d["data"], you need another type assertion:

test := d.(map[string]interface{})["data"].(map[string]interface{})["type"]
fmt.Println(test)

Then it will work. Output will be "domains". See a working example on the Go Playground.

Also note that if you declare d to be of type map[string]interface{}, you can spare the first type assertion:

var d map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&d); err != nil {
    panic(err)
}
test := d["data"].(map[string]interface{})["type"]
fmt.Println(test)

Output is the same. Try this one on the Go Playground.

If you need to do these and similar operations many times, you may find my github.com/icza/dyno library useful (whose primary goal is to aid working with dynamic objects).