Sort Decoded Records By A Numeric Field
Decode a JSON array of records, sort by a numeric field with slices.SortFunc, then re-encode so reports stop trusting upstream ordering.
Code
package main
import (
"cmp"
"encoding/json"
"fmt"
"slices"
)
// Decoded records arrive in arbitrary order; sort by the numeric field before reporting.
type Record struct {
User string `json:"user"`
Score float64 `json:"score"`
}
func main() {
payload := `[
{"user":"ana","score":81.5},
{"user":"bob","score":97},
{"user":"cid","score":72.25}
]`
var records []Record
if err := json.Unmarshal([]byte(payload), &records); err != nil {
fmt.Println("decode failed:", err)
return
}
// 数值字段降序:b 在前 a 在后即为逆序
slices.SortFunc(records, func(a, b Record) int {
return cmp.Compare(b.Score, a.Score)
})
out, err := json.Marshal(records)
if err != nil {
fmt.Println("encode failed:", err)
return
}
fmt.Println("sorted:", string(out))
}How it works
Everything happens inside the function main.
Error handling is inline: 2 places test err != nil and branch immediately.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Output arrives labeled — decode failed:, encode failed:, sorted: — when the file runs.
Key statements
if err != nil {
fmt.Println("encode failed:", err)
return
}
return cmp.Compare(b.Score, a.Score)
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.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.
FAQ
- What does Sort Decoded Records By A Numeric Field print when run?
- No setup needed: run the file and look for labeled lines like `decode failed:`, `encode failed:`, `sorted:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.