JSON Field Order Structs Versus Maps

Struct fields marshal in declaration order while map keys always come out sorted, so reproducible payloads and hashes choose their carrier deliberately.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"encoding/json"
	"fmt"
)

type Order struct {
	ID    string `json:"id"`
	Total int    `json:"total"`
}

func main() {
	// 结构体字段按声明顺序输出(declaration order),逐次一致
	order := Order{ID: "o-1", Total: 4200}
	encoded, _ := json.Marshal(order)
	fmt.Println("struct :", string(encoded))

	// map 的键始终按字典序输出(sorted keys),与插入顺序无关
	dynamic := map[string]any{"total": 4200, "id": "o-1", "zeta": true}
	encodedMap, _ := json.Marshal(dynamic)
	fmt.Println("map    :", string(encodedMap))

	// 同一份 map 每次编码结果相同,适合哈希与快照比对
	again, _ := json.Marshal(dynamic)
	fmt.Println("stable :", string(encodedMap) == string(again))
}

What the code does

Count the function main as the entire surface area of JSON Field Order Structs Versus Maps.

Applying it

The demo output is labeled (struct :, map :, stable :), so the printed lines read as a trace of the operations that ran.

Statements that matter most here

dynamic := map[string]any{"total": 4200, "id": "o-1", "zeta": true}

Interactive Tools for This Topic

FAQ

What does JSON Field Order Structs Versus Maps print when run?
Invoke the file as-is — the `struct :`, `map :`, `stable :` prefixes identify which step printed each line.