Hey. I had this problem. There is a string-json, which is converted to a map. Inside this line is an array. The problem is as follows. The Unmarshall function converts the string to json, after which I try to get the above array, but I get the error:

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

I give an example of json ʻa:

 map[lon:52.328066 fias_id:89bc3c83-6060-4737-a497-0d4e64cdff16 polygon_osm_id:0 path:Россия, Кировская область, Верхнекамский район, Пещера, Нижняя улица place_type: is_capital:0 official_status_ru: alt_names:[] info:{} id:376672 msg: type:street lat:59.192944 name:Нижняя улица parent_id:376618 parent_ids:[0 1 72 371251 376618]] 

I want to get parent_ids . I do it like this:

 parent := dataJson["parent_ids"].(map[int]int) // Здесь падает программа 

A piece of code that performs the conversion:

 json.Unmarshal(bytes, &dataJson) fmt.Println(dataJson) parent := dataJson["parent_ids"].(map[int]int) 

How to solve this problem?

  • one
    You also write that parent_ids is a slice, not a map. And by the way, your data normally falls on the structure, so why are you doing through the map ? - Ainar-G
  • I did not think about it. Probably do so. Could you tell me how to solve my question for me? Would you like to deal with him? - hedgehogues

1 answer 1

If the data scheme is more or less static, it is better to decode it into structures:

 type data struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` // ... ParentIDs []int `json:"parent_ids"` } // ... d := &data{} err := json.Unmarshal(body, d) fmt.Printf("err: %v parent IDs: %v", err, d.ParentIDs) 

Playground: https://play.golang.org/p/SpT1eb7Yys .


EDIT: if you have a non-static scheme, you will have to do it through a lot of asserts by type:

 parentIDsArr := dataJSON["parent_ids"].([]interface{}) parentIDs := []float64{} for _, id := range parentIDsArr { parentIDs = append(parentIDs, id.(float64)) } fmt.Println(parentIDs) 
  • Generally speaking, the structure is not static. Therefore, I would like to work with interfaces - hedgehogues
  • @hedgehogues See the edit. - Ainar-G
  • cannot use parent (type []interface {}) as type map[int]int in field value - hedgehogues
  • type: fmt.Println(reflect.TypeOf(dataJson["parent_ids"]) ) like this: []interface {} - hedgehogues
  • Where do you get map[int]int ? I tell you again, there is an array. - Ainar-G