-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
46 lines (41 loc) · 1.05 KB
/
json.go
File metadata and controls
46 lines (41 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package mapx
import "reflect"
var JSONEncoderFuncs = RegisterEncoder(EncoderFuncs{}, jsonAny)
func jsonAny(val any) (any, error) {
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(v.Uint()), nil
case reflect.String:
return v.String(), nil
case reflect.Bool:
return v.Bool(), nil
case reflect.Float32, reflect.Float64:
return v.Float(), nil
case reflect.Slice:
l := v.Len()
out := make([]any, 0, l)
for i := 0; i < l; i++ {
v, err := jsonAny(v.Index(i).Interface())
if err != nil {
return nil, err
}
out = append(out, v)
}
return out, nil
case reflect.Map:
out := make(map[string]any, v.Len())
for iter := v.MapRange(); iter.Next(); {
k, v := iter.Key(), iter.Value()
val, err := jsonAny(v.Interface())
if err != nil {
return nil, err
}
out[k.String()] = val
}
return out, nil
}
return val, nil
}