Im calling a API and it returns a dictionary(map) with a list of items as values.
For ex:-
result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}
The above data is how the data represented in python.
In Python, I directly use result['outputs'][0] to access the list of elements in the list.
In Golang, the same API returns the data but when I try to access the data as result['outputs'][0]
Get this error:-
invalid operation: result["outputs"][0] (type interface {} does not support indexing)
Looks like I need to do a type conversion, what should I use to type convert, I tried this
result["outputs"][0].(List)
result["outputs"][0].([])
but both throws me an error.
I checked the type of the returned item and this is it - []interface {}
What should be my type conversion?
You wrote the type of the value is []interface{}
, so then do a type assertion asserting that type.
Also note that you first have to type assert, and index later, e.g.:
outputs := result["outputs"].([]interface{})
firstOutput := outputs[0]
Also note that the (static) type of firstOutput
will again be interface{}
. To access its content, you will need another type assertion, most likely a map[string]interface{}
or a map[interface{}]interface{}
.
If you can, model your data with structs so you don't have to do this "type assertion nonsense".
Also note that there are 3rd party libs that support easy "navigation" inside dynamic objects such as yours. For one, there's github.com/icza/dyno
(disclosure: I'm the author).
Using dyno
, getting the first output would be like:
firstOutput, err := dyno.Get(result, "outputs", 0)
To get the country of the first output:
country, err := dyno.Get(result, "outputs", 0, "country")
You can also "reuse" previously looked up values, like this:
firstOutput, err := dyno.Get(result, "outputs", 0)
// check error
country, err := dyno.Get(firstOutput, "country")
// check error