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.

GoData Integrity

Code

gosnippet
40 lines
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

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.