ioutil.ReadAll() return type

Hi All

I am trying to parse data from a POST request from a client. I have used ioutil.ReadAll() for this purpose. But I noticed that the data returned is an array of uint8 when I printed it using log.Println().

body, err := ioutil.ReadAll(r.Body)
log.Println(body) // Gives out an array of uint8
log.Println(string(body)) // Gives a json string as passed in the POST request

How do I parse data out this? I tried unmarshalling and also decoders. They didn’t pan out well.
Thanks for your suggestions in advance. I am a newbie in golang and I am currently loving it.

This should do the trick:

package main

type myInfo struct { 
  ID number `json:"id"`
  Name string `json:"name"`
}

func main() {
  // ... 

  var info myInfo

  bytesBody, _ := ioutil.ReadAll(r.Body)
  defer r.Body.Close()

  // here's the trick
  json.Unmarshal(bytesBody, &info) 

  fmt.Println(info)
}

Edit: I didn’t check the error to make it more compact, don’t do that! :wink:
Edit2: For more info on the APIs, take a look at the docs: ioutil.ReadAll and json.Unmarshal.

1 Like

Please note that if you’re dealing with a reader to start with, there’s no reason to use ioutiul.ReadAll(r.Body), you should just call json.NewDecoder(r.Body).Decode(...) directly.

2 Likes

Thanks a lot…:slight_smile:

Hi. I just realised that the issue maybe with the client’s data format or something because when I do this or NewDecoder as pointed by @Luna I get an empty string/data. So how do I verify if the data obtained is in json format? I think it currently has come as a single string – “{“key1”:“value1”,“key2”:“value2”}”

This is what I found out by trying to convert individual bytes into string from the []byte that you get on unmarshalling.

Can you give an example of the real data? If you do something like…

b, err := ioutil.ReadAll(r.Body)
if err != nil { 
  panic(err) 
}
fmt.Println(string(b))

You can see the data you are getting.

Don’t do this, decoder is for streaming JSON structs, not for unmarshalling: https://ahmetalpbalkan.com/blog/golang-json-decoder-pitfalls/

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.