-1

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.

Alven Peng
  • 17
  • 3
  • 2
    Please don't post pictures of code - post actual code. – selbie Apr 18 '22 at 03:26
  • 3
    `json.Unmarshal` returns an error and tells you what's wrong exactly. Most likely however, the payload is either not JSON or it is JSON but it contains a value that does not "fit" into a map, like an array instead of an object for example. – mkopriva Apr 18 '22 at 03:31
  • 1
    Also, when you are printing bytes for debugging, help yourself and convert the bytes into a string, so that as a human you can actually read the output. – mkopriva Apr 18 '22 at 03:33

1 Answers1

3

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{}
selbie
  • 100,020
  • 15
  • 103
  • 173