简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM