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.

GoData Integrity

Code

gosnippet
36 lines
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

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:`.