JSON Unmarshal Into A Typed Struct
Decode a JSON object into a struct with json tags so missing fields keep their zero values and type mismatches surface as explicit errors.
Code
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
Host string `json:"host"`
Port int `json:"port"`
TLSEnabled bool `json:"tls"`
}
func main() {
payload := `{"host": "api.devexamples.com", "port": 443}`
var s Server
if err := json.Unmarshal([]byte(payload), &s); err != nil {
fmt.Println("decode failed:", err)
return
}
// 缺失字段保持零值,不做隐式猜测
fmt.Printf("%s:%d tls=%v\n", s.Host, s.Port, s.TLSEnabled)
// 类型不匹配立刻报错,而不是静默塞进零值
bad := `{"host": "h", "port": "not-a-number"}`
err := json.Unmarshal([]byte(bad), &s)
fmt.Println("bad type error:", err != nil)
}Inside the snippet
JSON Unmarshal Into A Typed Struct is built around the function main.
err is inspected at 1 call site before any result is trusted.
Points of care
- No package manager involved — every call resolves to a built-in API.
Putting it to use
Signature: func main()
The run emits 2 labeled sections — decode failed:, bad type error: — one per step.
Core lines
payload := `{"host": "api.devexamples.com", "port": 443}`
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 does JSON Unmarshal Into A Typed Struct print when run?
- Run it as a complete program — the output lines carry labels such as `decode failed:`, `bad type error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.