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

尝试遍历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

当我尝试遍历某些json映射时遇到问题。 p>

原始JSON数据如下: p>

 “ dataArray”:[
 {
“ name”:“ default”,
“  url“:” / some / url“ 
},
 {
” name“:” second“,
” url“:” / another / url“ 
} 
] 
  code>   pre> 
 
 

地图看起来像这样: p>

  [map [name:default url:/ some / url] map [name:second url]  :/ another / url]] 
  code>  pre> 
 
 

代码看起来像这样: p>

  for _,urlItem:= 范围项目。(map [string] interface {}){
做一些事情
} 
  code>  pre> 
 
 

当它是JSON对象时通常可以使用,但这是 JSON中的一个数组,我得到以下错误: p>

panic:接口转换:interface {}是[] interface {},而不是map [string] interface { } p> blockquote>

任何帮助将不胜感激 p> div>

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
}