我调用一个API,它返回一个字典(地图),其中有一个项目列表作为值。
例如:
1 | result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]} |
上面的数据是用python表示的数据。
在Python中,我直接使用result ['outputs'] [0]访问列表中的元素列表。
在Golang中,相同的API返回数据,但是当我尝试以result ['outputs'] [0]访问数据时
得到这个错误:
1 | invalid operation: result["outputs"][0] (type interface {} does not support indexing) |
看起来我需要进行类型转换,应该使用什么类型进行转换,
我试过了
1 2 | result["outputs"][0].(List) result["outputs"][0].([]) |
但两者都给我带来了一个错误。
我检查了返回项目的类型,它就是它-[] interface {}
我的类型转换应该是什么?
- 您可以显示用于获得不良结果的代码吗?
您将值的类型写为
另请注意,您首先必须输入assert,然后再进行索引,例如:
1 2 3 | outputs := result["outputs"].([]interface{}) firstOutput := outputs[0] |
另请注意,
如果可以的话,请使用结构为数据建模,这样就不必进行"类型断言废话"了。
还请注意,有第3方库支持在诸如您的动态对象内进行轻松的"导航"。 首先,是
使用
1 | firstOutput, err := dyno.Get(result,"outputs", 0) |
获取第一个输出的国家:
1 | country, err := dyno.Get(result,"outputs", 0,"country") |
您还可以"重用"以前查找的值,如下所示:
1 2 3 4 | firstOutput, err := dyno.Get(result,"outputs", 0) // check error country, err := dyno.Get(firstOutput,"country") // check error |