Scan Nullable SQL Columns Safely
Map nullable database columns into sql.NullString and *string fields, then emit clean nulls through a custom JSON view.
Code
package main
import (
"database/sql"
"encoding/json"
"fmt"
)
type Profile struct {
ID int64 `json:"id"`
Nickname sql.NullString `json:"-"`
Bio *string `json:"bio"`
}
type profileJSON struct {
ID int64 `json:"id"`
Nickname *string `json:"nickname"`
Bio *string `json:"bio"`
}
func nullString(value sql.NullString) *string {
if !value.Valid {
return nil
}
return &value.String
}
func (p Profile) MarshalJSON() ([]byte, error) {
return json.Marshal(profileJSON{
ID: p.ID,
Nickname: nullString(p.Nickname),
Bio: p.Bio,
})
}
func scanProfile(row *sql.Row) (Profile, error) {
var profile Profile
err := row.Scan(&profile.ID, &profile.Nickname, &profile.Bio)
return profile, err
}
func main() {
encoded, _ := json.Marshal(Profile{ID: 7})
fmt.Println(string(encoded))
encoded, _ = json.Marshal(Profile{
ID: 8,
Nickname: sql.NullString{String: "ada", Valid: true},
})
fmt.Println(string(encoded))
}
Inside the snippet
The working surface is the functions nullString, MarshalJSON, scanProfile and main — everything else is wiring.
Putting it to use
The primary signature is func (p Profile) MarshalJSON() ([]byte, error)
Core lines
func scanProfile(row *sql.Row) (Profile, error) {
var profile Profile
err := row.Scan(&profile.ID, &profile.Nickname, &profile.Bio)
return profile, err
}
func (p Profile) MarshalJSON() ([]byte, error) {
return json.Marshal(profileJSON{
ID: p.ID,
Nickname: nullString(p.Nickname),
Bio: p.Bio,
})
}
func nullString(value sql.NullString) *string {
if !value.Valid {
return nil
}
return &value.String
}
Interactive Tools for This Topic
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.
FAQ
- How do you run Scan Nullable SQL Columns Safely?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.