【发布时间】:2021-06-22 15:41:47
【问题描述】:
长期聆听,第一次来电!
我是 Go 的初学者,但有几年的 Python 经验。所以,请原谅我的无知。
所以,我正在尝试将来自 Web 服务器的多级 json 响应解析为 map[string]interface{} 类型。
例子:
func GetResponse() (statusCode int, responseData map[string]interface{}){
host := "https://somebogusurl.com/fake/json/data"
request, err := http.NewRequest("GET", host, nil)
if err != nil {
panic(err)
}
client := http.Client{}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
data, _ := ioutil.ReadAll(response.Body)
json.Unmarshal([]byte(data), &responseData)
return response.StatusCode, responseData
}
func main() {
statusCode, data := GetResponse()
fmt.Println(data["foo"].(map[string]interface{})["bar"])
}
如您所见,我正在尝试访问返回的这个新映射中的嵌套值。但是,我收到以下错误:
panic: interface conversion: interface {} is []interface {}, not map[string]interface {}
我相信我正在尝试访问位于接口中的嵌套数据,而不是基于错误的 map[string]interface。知道如何访问嵌套数据吗?
【问题讨论】:
-
这能回答你的问题吗? golang how to access interface fields
标签: json dictionary go interface