Golang中sqlx输出顺序随机反转及前缀去除问题咨询
Hey there! Let's tackle those two SQLx-related issues you're facing—they're pretty common when working with maps in Go, so I've got you covered.
1. Why does the output order of map entries randomly reverse?
This is intentional behavior in Go! The map[string]interface{} type (and all Go maps, for that matter) has unordered key-value pairs by design. Go randomizes map iteration order to prevent developers from relying on a specific sequence (which would break if the map implementation changes down the line). Even if you populate the map with keys in the same order every time, a subsequent range loop might spit them out in a different order.
If you need a consistent, predictable output order, you'll need to:
- Extract all map keys into a slice
- Sort the slice
- Iterate over the sorted slice to access map values in order
Here's a quick example tailored to your use case:
import "sort" // Your existing map from SQLx resultMap := map[string]interface{}{"SIGN_NAME":"Chris Walker", "SIGN_ID":"CW"} // Extract and sort keys keys := make([]string, 0, len(resultMap)) for k := range resultMap { keys = append(keys, k) } sort.Strings(keys) // Iterate in sorted order for _, k := range keys { fmt.Printf(`"%s":"%v"`, k, resultMap[k]) }
2. How to remove the map[string]interface {} prefix from output?
That prefix comes from using Go's default fmt package methods (like fmt.Println or fmt.Printf("%#v", map)), which print both the type and contents of the map. To get clean output without the type info, you have a few solid options:
Option 1: Marshal to JSON (most straightforward)
Convert the map to a JSON string—this gives you clean, readable output without any type clutter, and it's perfect for logging or API responses:
import "encoding/json" resultMap := map[string]interface{}{"SIGN_NAME":"Chris Walker", "SIGN_ID":"CW"} // Marshal with indentation for readability jsonOutput, err := json.MarshalIndent(resultMap, "", " ") if err != nil { panic(err) // Handle error properly in production code } fmt.Println(string(jsonOutput))
This will output:
{ "SIGN_ID": "CW", "SIGN_NAME": "Chris Walker" }
Option 2: Build a custom string manually
If you want a format closer to your original example (without JSON's strict structure), you can construct the string yourself:
import "strings" resultMap := map[string]interface{}{"SIGN_NAME":"Chris Walker", "SIGN_ID":"CW"} var sb strings.Builder sb.WriteString("{") firstEntry := true // Use sorted keys here if you want consistent order too! for k, v := range resultMap { if !firstEntry { sb.WriteString(", ") } sb.WriteString(fmt.Sprintf(`"%s":"%v"`, k, v)) firstEntry = false } sb.WriteString("}") fmt.Println(sb.String())
This will output something like:
{"SIGN_ID":"CW", "SIGN_NAME":"Chris Walker"}
内容的提问来源于stack exchange,提问作者sibert

