This repository has been archived by the owner on Sep 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jonsonizers.go
104 lines (95 loc) · 2.02 KB
/
jonsonizers.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
Written by Daniel Krom
2018
*/
package jonson
import (
"reflect"
)
func jonsonize(value interface{}) *JSON {
if value == nil {
return NewEmptyJSON()
}
vo := reflect.ValueOf(value)
if vo.Kind() == reflect.Ptr {
vo = vo.Elem()
value = vo.Interface()
}
switch vo.Kind() {
case reflect.Ptr:
return jonsonize(vo.Elem())
case reflect.Map:
return jonsonizeMap(&vo)
case reflect.Slice:
return jonsonizeSlice(&vo)
case reflect.String,
reflect.Bool,
reflect.Float64,
reflect.Float32,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
return &JSON{
value: value,
isPrimitive: true,
kind: vo.Kind(),
}
case reflect.Struct:
if v, ok := value.(JSON); ok {
return v.Clone()
}
return jonsonizeStruct(&vo)
}
return NewEmptyJSON()
}
func jonsonizeMap(value *reflect.Value) *JSON {
mapValue := make(map[string]*JSON)
for _, k := range value.MapKeys() {
// map should be only string as keys
keyType := reflect.TypeOf(k.Interface())
if keyType.Kind() != reflect.String {
continue
}
mapValue[k.Interface().(string)] = jonsonize(value.MapIndex(k).Interface())
}
return &JSON{
value: mapValue,
isPrimitive: false,
kind: reflect.Map,
}
}
func jonsonizeSlice(value *reflect.Value) *JSON {
arrValue := make([]*JSON, value.Len())
for i := 0; i < value.Len(); i++ {
arrValue[i] = jonsonize(value.Index(i).Interface())
}
return &JSON{
value: arrValue,
isPrimitive: false,
kind: reflect.Slice,
}
}
func jonsonizeStruct(vo *reflect.Value) *JSON {
tempMap := make(map[string]interface{})
typ := vo.Type()
for i := 0; i < typ.NumField(); i++ {
if vo.Field(i).CanInterface() {
fieldValue := typ.Field(i)
if v, has := fieldValue.Tag.Lookup("json"); has {
if v != "-" {
tempMap[v] = vo.Field(i).Interface()
}
continue
}
tempMap[fieldValue.Name] = vo.Field(i).Interface()
}
}
return jonsonize(&tempMap)
}