I am new to golang and trying to map database query result to my struct which is nested but I am getting errors and not able to figure out the best way to do it. This program is suppose to out JSON - book details group by categories.
Struct is as follows
type book struct{
category string
books []*bookDetails
}
type bookDetails struct{
name string
id uint
publisher string.
}
Expected JSON output
[
{
"category" : "Ficton",
"books" : [
{name:'aaa',id:12,publisher:'one'},
{name:'bbb',id:13,publisher:'two'}
]
},
{
"category" : "suspense",
"books" : [
{name:'ccc',id:14,publisher:'three'},
{name:'ddd',id:15,publisher:'four'}
]
}
]
I am not writing SQL query here but please assume similar kind of database schema. dbRow in following code is output of select query. Following code is working fine but I am getting all the books in one array, and I am not able to figure out how can I make it group by categories.
detailsMap := make(map[uint][]*details)
for dbRow.Next() {
var det details
detErr := dbRow.StructScan(&det)
detailsMap[det.id] = append(detailsMap[det.id], &det)
}