Try to convert json to map for golang web application

1.6k Views Asked by At

I am writing a web application using golang. This app tries to use the api of gitea. My task is to get json and convert it to map. First I get the response.body and convert it to []byte by using ioutil.readAll(), then I use Unmarshal() to convert it to map. I can get the response.body in []byte format. However, there is no element in map. Does anyone know the reason?

code

enter image description here

you can see that the map is empty but I can get response.Body in []byte format.

1

There are 1 best solutions below

0
On

Your picture that shows the dump of responseData byte, the first integer value in that array is 91. In ascii, that's a left bracket, [, or rather the start of an array. The second byte, 123, is a left curly brace, or {

Decoding your first few bytes:

[{"id":3,"url":"http://...

Hence, your response body is not a json object, but rather it's more likely to be a json array containing json objects.

Do this instead:

var items []interface{}
err := json.Unmarshal(responseData, &items)

If all goes well, your items array is filled up with an array of map[string]interface{} instances. That assumes that all items in the array are json objects to begin with.

And if you know for certain that it's always an array of objects, you can declare items as this instead (an array of maps).

var items []map[string]interface{}