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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.