JSON ,string Tag Quotes Numeric Fields
The ,string struct tag option encodes numeric fields as quoted JSON strings and decodes them back, enforcing quoted-number wire contracts on both sides.
Code
package main
import (
"encoding/json"
"fmt"
)
// A legacy gateway contract sends numbers as JSON strings: the ,string option quotes them automatically
type Config struct {
Port int `json:"port,string"`
Timeout int64 `json:"timeout_ms,string"`
Retries uint8 `json:"retries,string"`
Host string `json:"host"`
}
func main() {
// Encoding: all three numeric fields emit as quoted strings
payload, err := json.Marshal(Config{Port: 8080, Timeout: 1500, Retries: 3, Host: "internal"})
if err != nil {
panic(err)
}
fmt.Println(string(payload))
// Decoding: quoted numbers are restored to their numeric types automatically
var cfg Config
quoted := []byte(`{"port":"9090","timeout_ms":"800","retries":"1","host":"backup"}`)
if err := json.Unmarshal(quoted, &cfg); err != nil {
panic(err)
}
fmt.Printf("port=%d timeout=%d retries=%d host=%s\n", cfg.Port, cfg.Timeout, cfg.Retries, cfg.Host)
// The contract is enforced: a bare number violates ,string and decoding fails outright
var bad Config
err = json.Unmarshal([]byte(`{"port":9090}`), &bad)
fmt.Println("bare number rejected:", err != nil)
}How it works
JSON ,string Tag Quotes Numeric Fields is built around the function main.
Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
Watch out for
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Using it
Output lines are prefixed (port=, bare number rejected:), so the printed lines keep their steps identifiable.
Key statements
if err != nil {
panic(err)
}
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What is the error handling style?
- The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
- What does JSON ,string Tag Quotes Numeric Fields print when run?
- The script runs standalone; its 2 labeled outputs include `port=`, `bare number rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.