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.
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!
Edit2: For more info on the APIs, take a look at the docs: ioutil.ReadAll and json.Unmarshal.
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.
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.