尝试遍历json数组的映射时出现Golang接口转换错误

I'm having an issue when I'm try to iterate through a map of some json.

The original JSON data looks like this:

"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:

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}

Any help would be greatly appreciated

The error is :

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}

in your code you're converting item into 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.

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. not map.

First you can convert your data to []interface{} and then get the index of that and convert it to 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
}