Dictionary 项目列表的Golang类型断言

Dictionary 项目列表的Golang类型断言,dictionary,go,slice,type-assertion,Dictionary,Go,Slice,Type Assertion,我正在调用一个API,它返回一个字典(map),其中包含一个项目列表作为值 例如:- result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]} 上面的数据是如何用python表示数据的 在Python中,我直接使用result['outputs'][0]访问列表中的元素列表 在Golang中,相同的API返回数据,但当我尝试访问数据作为结果['outputs'][0] 获取此错误:- i

我正在调用一个API,它返回一个字典(map),其中包含一个项目列表作为值

例如:-

result= {'outputs':[{'state':'md','country':'us'}, {'state':'ny','country':'ny'}]}
上面的数据是如何用python表示数据的

在Python中,我直接使用result['outputs'][0]访问列表中的元素列表

在Golang中,相同的API返回数据,但当我尝试访问数据作为结果['outputs'][0]

获取此错误:-

invalid operation: result["outputs"][0] (type interface {} does not support indexing)
看起来我需要进行类型转换,我应该使用什么进行类型转换, 我试过这个

result["outputs"][0].(List)
result["outputs"][0].([])
但两者都给我带来了一个错误

我检查了返回项的类型,这是-[]接口{}


我的类型转换应该是什么?

您编写的值的类型是
[]接口{}
,因此请断言该类型

还要注意,您首先必须键入assert,然后键入index,例如:

outputs := result["outputs"].([]interface{})

firstOutput := outputs[0]
还请注意,
firstOutput
的(静态)类型也将是
interface{}
。要访问其内容,您将需要另一个类型断言,很可能是
map[string]interface{}
map[interface{}]interface{}

如果可以,可以使用结构对数据建模,这样就不必执行这种“类型断言胡说八道”

还请注意,有第三方LIB支持在动态对象(如您的动态对象)中轻松“导航”。首先,有(披露:我是作者)

使用
dyno
,获取第一个输出如下:

firstOutput, err := dyno.Get(result, "outputs", 0)
要获取第一次输出的国家/地区,请执行以下操作:

country, err := dyno.Get(result, "outputs", 0, "country")
您还可以“重用”以前查找的值,如下所示:

firstOutput, err := dyno.Get(result, "outputs", 0)
// check error
country, err := dyno.Get(firstOutput, "country")
// check error

你能展示你用来得到不想要的结果的代码吗?