I am getting the below response in a URL and I want to unmarshal it, but I am unable to do so. This is the kind of response that I'd like to unmarshal.
[
{"title": "Angels And Demons", "author":"Dan Brown", "tags":[{"tagtitle":"Demigod", "tagURl": "/angelDemon}] }
{"title": "The Kite Runner", "author":"Khalid Hosseinei", "tags":[{"tagtitle":"Kite", "tagURl": "/kiteRunner"}] }
{"title": "Dance of the dragons", "author":"RR Martin", "tags":[{"tagtitle":"IronThrone", "tagURl": "/got"}] }
]
I am trying to unmarshal this sort of response but not being able to do so. This is the code that I am trying to write.
res, err := http.Get(url)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Couldn't get the html response")
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Couldn't read the response")
}
s := string(b)
var data struct {
Content []struct {
Title string `json:"title"`
Author string `json:"author"`
Tags map[string]string `json:"tags"`
}
}
if err := json.Unmarshal([]byte(s), &data); err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Un-marshalling could not be done.")
}
fmt.Println(data.Content)
Can anyone please help me in this regard? Thanks in advance.
Change it
var data struct {
Content []struct {
Title string `json:"title"`
Author string `json:"author"`
Tags map[string]string `json:"tags"`
} }
to this
type Content struct {
Title string `json:"title"`
Author string `json:"author"`
Tags map[string]string `json:"tags"`
}
var data []Content
Consider unmarshalling it into a slice of Content:
type Content struct {
Title string `json:"title"`
Author string `json:"author"`
Tags map[string]string `json:"tags"`
}
// Send in your json
func convertToContent(msg string) ([]Content, error) {
content := make([]Content, 0, 10)
buf := bytes.NewBufferString(msg)
decoder := json.NewDecoder(buf)
err := decoder.Decode(&content)
return content, err
}
Check out an example with your use case here: http://play.golang.org/p/TNjb85XjpP
I was able to sort out this issue by doing a simple amendment in the above code.
var Content []struct {
Title string `json:"title"`
Author string `json:"author"`
Tags map[string]string `json:"tags"`
}
Thanks for all your responses.