I'm using golang. My database model is: type Sport struct { ID int64 Name string } my…
- User
I'm using golang. My database model is: type Sport struct {
ID int64
Name string
}my database query is like this:
func (q *Queries) GetSports(ctx context.Context) ([]Sport, error) { rows, err := q.db.Query(ctx, getSports) if err != nil { return nil, err } defer rows.Close() var items []Sport for rows.Next() { var i Sport if err := rows.Scan(&i.ID, &i.Name); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil }
I want to return json to my frontend like [{id:1,name:"somename"},...] How do I get it to format it nicely to the intended json?
My handler so far: func (h *Handler) HandleGetSports(w http.ResponseWriter, r *http.Request) { sports, err := h.service.queries.GetSports(r.Context())
if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) response := common.ApiResponse{ Success: true, Data: sports, } json.NewEncoder(w).Encode(response) return}
- Assistant
In Go the json encoder looks at the field names that are exported in your struct.
If you don’t tell it otherwise it will use those names verbatim, which is why you are currently getting something like:[ {"ID":1,"Name":"Football"}, ... ]All you have to do is add JSON tags to the struct so the encoder knows which key to use.
type Sport struct { ID int64 `json:"id"` Name string `json:"name"` }Nothing else in your code has to change—
encoding/jsonwill automatically use those tags when you calljson.NewEncoder(...).Encode(...).
Complete example
// db model ------------------------------------------------------------ type Sport struct { ID int64 `json:"id"` Name string `json:"name"` } // query function (unchanged) ------------------------------------------ func (q *Queries) GetSports(ctx context.Context) ([]Sport, error) { rows, err := q.db.Query(ctx, getSports) if err != nil { return nil, err } defer rows.Close() var items []Sport for rows.Next() { var i Sport if err := rows.Scan(&i.ID, &i.Name); err != nil { return nil, err } items = append(items, i) } return items, rows.Err() } // response wrapper ----------------------------------------------------- type ApiResponse struct { Success bool `json:"success"` Data interface{} `json:"data,omitempty"` Error string `json:"error,omitempty"` } // HTTP handler --------------------------------------------------------- func (h *Handler) HandleGetSports(w http.ResponseWriter, r *http.Request) { sports, err := h.service.queries.GetSports(r.Context()) if err != nil { writeJSON(w, http.StatusInternalServerError, ApiResponse{ Success: false, Error: err.Error(), }) return } writeJSON(w, http.StatusOK, ApiResponse{ Success: true, Data: sports, }) } // small helper --------------------------------------------------------- func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) // ignore error for brevity }The front-end will now receive exactly:
{ "success": true, "data": [ { "id": 1, "name": "Football" }, { "id": 2, "name": "Baseball" } ] }(Or if you prefer to send only the array, simply encode
sportsdirectly instead of wrapping it inApiResponse.) - User
I should add that I'm using sqlc and I can't modify the database models
- Assistant
With sqlc you can get proper JSON out without touching the generated code—you just have to tell sqlc to emit JSON tags when it builds the structs.
- Turn on the flag in
sqlc.yaml(orsqlc.json, whichever you use):
version: "2" sql: - engine: "postgresql" schema: "schema.sql" queries: "query.sql" gen: go: package: "db" out: "db" emit_json_tags: true # <── add this lineNow when you run
sqlc generate, the produced struct will look like:type Sport struct { ID int64 `json:"id"` Name string `json:"name"` }Nothing else in your code needs to change;
json.NewEncoderwill automatically create[{ "id": 1, "name": "somename" }, ...]- If you can’t (or don’t want to) change the
sqlcconfig, make a small DTO (data-transfer object) and copy:
type SportDTO struct { ID int64 `json:"id"` Name string `json:"name"` } func toDTO(src []db.Sport) []SportDTO { out := make([]SportDTO, len(src)) for i, s := range src { out[i] = SportDTO{ID: s.ID, Name: s.Name} } return out }Then encode
toDTO(sports)instead ofsports.But the first option—
emit_json_tags: true—is by far the easiest and keeps the codebase clean. - Turn on the flag in
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.