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.
Code
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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.