generated from devnw/oss-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
197 lines (181 loc) · 3.73 KB
/
json.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package ajson
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"go.devnw.com/structs"
)
// MarshalJSON marshals the given struct to json and then merges
// the unknown fields into the json from the map[string]any object
//
// Example usage:
//
// type Sample struct {
// Name string `json:"name"`
// Age int `json:"age"`
// Sub *SubSample `json:"sub,omitempty"`
// }
//
// type SubSample struct {
// Name string `json:"name"`
// }
//
// func main() {
// sample := Sample{
// Name: "John",
// Age: 30,
// }
//
// unknowns := map[string]any{
// "location": "USA",
// }
//
// data, err := MarshalJSON(sample, unknowns)
// if err != nil {
// panic(err)
// }
//
// fmt.Println(string(data))
// }
//
// // Output:
// // {"name":"John","age":30,"location":"USA"}
//
// Example with embeded unknown and custom marshaler:
//
// type Sample struct {
// Name string
// Age int
// Unknowns map[string]any
// }
//
// func (s Sample) MarshalJSON() ([]byte, error) {
// return MarshalJSON(struct {
// ID string `json:"id"`
// Name string `json:"name"`
// }{
// ID: t.ID,
// Name: t.Name,
// }, t.Unknowns)
// }
func Marshal[T comparable](t T, mm map[string]any) ([]byte, error) {
s := structs.New(t)
s.TagName = "json"
m := s.Map()
for key, value := range mm {
recurseMap(m, strings.Split(key, "."), value)
}
return json.Marshal(m)
}
func recurseMap(m map[string]any, path []string, value any) {
if len(path) == 1 {
m[path[0]] = value
return
}
// if there are more than one path, we need to find the
// correct map to set the value
// e.g. "sub.name" -> m["sub"].(map[string]any)["name"]
found := false
for key, v := range m {
if key == path[0] {
subMap, ok := v.(map[string]any)
if !ok {
continue
}
recurseMap(subMap, path[1:], value)
found = true
}
}
if !found {
newSubMap := make(map[string]any)
recurseMap(newSubMap, path[1:], value)
m[path[0]] = newSubMap
}
}
// UnmarshalJSON unmarshals the given json into the given struct
// and then returns the unknown fields as a map[string]any object.
//
// Example usage:
//
// type Sample struct {
// Name string `json:"name"`
// Age int `json:"age"`
// Sub *SubSample `json:"sub,omitempty"`
// }
//
// type SubSample struct {
// Name string `json:"name"`
// }
//
// func main() {
// data := []byte(`{"name":"John","age":30,"location":"USA"}`)
//
// var sample Sample
// unknowns, err := UnmarshalJSON(data, &sample)
// if err != nil {
// panic(err)
// }
//
// fmt.Println(sample)
// fmt.Println(unknowns)
// }
//
// // Output:
// // {John 30 &{ }}
// // map[location:USA]
//
// Example with embeded unknown and custom unmarshaler:
//
// type Sample struct {
// Name string
// Age int
// Unknowns map[string]any
// }
//
// func (s *Sample) UnmarshalJSON(data []byte) error {
// var t struct {
// ID string `json:"id"`
// Name string `json:"name"`
// }
//
// unknowns, err := UnmarshalJSON(data, &t)
// if err != nil {
// return err
// }
//
// s.Name = t.Name
// s.Age = t.Age
// s.Unknowns = unknowns
//
// return nil
// }
func Unmarshal[T comparable](data []byte) (T, map[string]any, error) {
mm := map[string]any{}
var t T
err := json.Unmarshal(data, &t)
if err != nil {
return t, mm, err
}
err = json.Unmarshal(data, &mm)
if err != nil {
return t, mm, err
}
tpe := reflect.TypeOf(t)
for i := 0; i < tpe.NumField(); i++ {
field := tpe.Field(i)
tagDetail := field.Tag.Get("json")
if tagDetail == "" {
// ignore if there are no tags
continue
}
options := strings.Split(tagDetail, ",")
if len(options) == 0 {
return t, mm,
fmt.Errorf("no tags options found for %s", field.Name)
}
// the first one is the json tag
delete(mm, options[0])
}
return t, mm, nil
}