更新时间:2021-09-08 23:24:14
d
的类型为interface{}
,因此您不能像d["data"]
那样对其进行索引,您需要另一个类型声明:
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)
然后它将起作用.输出将为"domains"
.请参见游乐场.
Then it will work. Output will be "domains"
. See a working example on the Go Playground.
还请注意,如果您声明d
的类型为map[string]interface{}
,则可以保留第一个类型的断言:
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.
如果您需要多次执行这些操作和类似操作,则可能会发现我的 github.com/icza/dyno
库很有用(其主要目标是帮助处理动态对象).
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).