Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

I'm using golang. My database model is: type Sport struct { ID int64 Name string } my…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. 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
    

    }

  2. 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/json will automatically use those tags when you call json.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 sports directly instead of wrapping it in ApiResponse.)

  3. User

    I should add that I'm using sqlc and I can't modify the database models

  4. 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.

    1. Turn on the flag in sqlc.yaml (or sqlc.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 line
    

    Now 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.NewEncoder will automatically create

    [{ "id": 1, "name": "somename" }, ...]
    
    1. If you can’t (or don’t want to) change the sqlc config, 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 of sports.

    But the first option—emit_json_tags: true—is by far the easiest and keeps the codebase clean.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.