type Country struct {
ID int `json:"id"`
States string `json:"states"`
}
func getAllCountries() {
rows, err := db.Query("select id, states from countries")
if err != nil {
astilog.Error(err)
}
defer rows.Close()
for rows.Next() {
var id int
var states string
err := rows.Scan(&id, &states)
if err != nil {
astilog.Error(err)
}
Countries = append(Countries, Country{id, states})
}
}
See (fictional) code above.
This is something I've been struggling with for a while.
In the past, I'd simply accept the string representation of a JSON array and operate on that directly.
However, that's less flexible and certainly less elegant.
What's the correct way of turning the above code into something a bit more canonical?
Since SQLite doesn't know of arrays, I obviously need to somehow cast the array to a string representation somewhere before "rows.Scan". Which is the part I'm struggling with.
The data presentation I'm hoping for looks as follows:
type Country struct {
ID int `json:"id"`
States []State `json:"states"`
}
type State struct {
Short string `json:"short"`
Population int `json:"population"`
}