JSON Marshal Sorts Map Keys

json.Marshal sorts map keys before encoding, so map output is byte-stable across runs, while struct fields keep declaration order instead.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// map 的键在 json.Marshal 时自动排序:输出与插入顺序无关
	scores := map[string]int{
		"zeta":  3,
		"alpha": 1,
		"mu":    2,
	}
	out, err := json.Marshal(scores)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))

	// 结构体字段按声明顺序输出,不做排序:与 map 行为不同
	type Point struct {
		Y int `json:"y"`
		X int `json:"x"`
	}
	p := Point{Y: 2, X: 1}
	structOut, _ := json.Marshal(p)
	fmt.Println(string(structOut))

	// 同一 map 多次 marshal 逐字节一致:确定性输出适合快照对比
	first, _ := json.Marshal(scores)
	second, _ := json.Marshal(scores)
	fmt.Println("stable:", string(first) == string(second))
}

The route from code to output

JSON Marshal Sorts Map Keys comes down to the function main.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Points of care

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Using it

The demo output is labeled (stable:), so every line in the printed output names the step that produced it.

Key statements

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
What does JSON Marshal Sorts Map Keys print when run?
No setup needed: run the file and look for labeled lines like `stable:` in the output.