[英]Golang interface conversion error when trying to iterate through map of json array
I'm having an issue when I'm try to iterate through a map of some json. 当我尝试遍历一些json映射时遇到问题。
The original JSON data looks like this: 原始JSON数据如下所示:
"dataArray": [
{
"name": "default",
"url": "/some/url"
},
{
"name": "second",
"url": "/another/url"
}
]
the map looks like this: 该地图如下所示:
[map[name:default url:/some/url] map[name:second url:/another/url]]
The code looks like this: 代码如下:
for _, urlItem := range item.(map[string]interface{}){
do some stuff
}
This normally works when it's a JSON object, but this is an array in the JSON and I get the following error: 当它是JSON对象时,这通常可以正常工作,但这是JSON中的数组,并且出现以下错误:
panic: interface conversion: interface {} is []interface {}, not map[string]interface {} panic:接口转换:interface {}是[] interface {},而不是map [string] interface {}
Any help would be greatly appreciated 任何帮助将不胜感激
The error is : 错误是:
panic: interface conversion: interface {} is []interface {}, not map[string]interface {} panic:接口转换:interface {}是[] interface {},而不是map [string] interface {}
in your code you're converting item
into map[string]interface{}
: 在您的代码中,您正在将item
转换为map[string]interface{}
:
for _, urlItem := range item.(map[string]interface{}){
do some stuff
}
But the actual item
is []interface {}
: change your covert type to this. 但是实际的item
是[]interface {}
:将您的隐蔽类型更改为此。
Because as you can see your result data is : 因为如您所见,结果数据为:
[map[name:default url:/some/url] map[name:second url:/another/url]]
it is an array
that has map
. 它是一个具有map
的array
。 not map
. 没有map
。
First you can convert your data to []interface{}
and then get the index of that and convert it to map[string]interface{}
. 首先,您可以将数据转换为[]interface{}
,然后获取该索引并将其转换为map[string]interface{}
。 so an example will look like this : 因此,示例如下所示:
data := item.([]interface{})
for _,value := range data{
yourMap := value.(map[string]interface{})
//name value
name := yourMap["name"].(string) // and so on
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.