3

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

4
  • Why not just tag some structs and Unmarshal the JSON the sane way? Commented Mar 30, 2017 at 15:39
  • I would, but sometimes the data is there and other times it isn't so I need to test the data before it goes in. It's a pain, but if there is no data to go in an array then the field that holds the array doesn't exist. Commented Mar 30, 2017 at 15:47
  • You mean the field in the JSON doesn't exist? You can just check for nil in that case. Commented Mar 30, 2017 at 15:55
  • 1
    Try this play.golang.org/p/Y79-0eWJyg Commented Mar 30, 2017 at 16:01

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.