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.

GoData Integrity

Code

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

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