MCPcopy Create free account
hub / github.com/astercloud/aster / normalizeMap

Function normalizeMap

pkg/util/json.go:74–113  ·  view source on GitHub ↗

normalizeMap 按 key 排序处理 map

(v reflect.Value)

Source from the content-addressed store, hash-verified

72
73// normalizeMap 按 key 排序处理 map
74func normalizeMap(v reflect.Value) any {
75 if v.IsNil() {
76 return nil
77 }
78
79 // 获取所有 key 并排序
80 keys := v.MapKeys()
81 sortedKeys := make([]string, 0, len(keys))
82 keyMap := make(map[string]reflect.Value, len(keys))
83
84 for _, k := range keys {
85 // 将 key 转换为字符串用于排序
86 var keyStr string
87 switch k.Kind() {
88 case reflect.String:
89 keyStr = k.String()
90 default:
91 // 对于非字符串 key,序列化为 JSON 字符串
92 keyBytes, _ := json.Marshal(k.Interface())
93 keyStr = string(keyBytes)
94 }
95 sortedKeys = append(sortedKeys, keyStr)
96 keyMap[keyStr] = k
97 }
98
99 sort.Strings(sortedKeys)
100
101 // 构建有序的 map(使用 orderedMap 保持顺序)
102 result := make(orderedMap, 0, len(sortedKeys))
103 for _, keyStr := range sortedKeys {
104 k := keyMap[keyStr]
105 val := v.MapIndex(k)
106 result = append(result, orderedMapEntry{
107 Key: keyStr,
108 Value: normalizeValue(val),
109 })
110 }
111
112 return result
113}
114
115// orderedMapEntry 有序 map 的条目
116type orderedMapEntry struct {

Callers 1

normalizeValueFunction · 0.85

Calls 3

normalizeValueFunction · 0.85
KindMethod · 0.65
StringMethod · 0.45

Tested by

no test coverage detected