/
json_parser.go
executable file
·577 lines (428 loc) · 12.8 KB
/
json_parser.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
package support
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/context"
"github.com/mobilemindtec/go-utils/app/util"
"github.com/mobilemindtec/go-utils/v2/optional"
)
type FormatType int64
const (
FormatTypeFloat FormatType = iota + 1
FormatTypeInt
FormatTypeDate
FormatTypeBool
)
type FormJsonConfig struct {
FieldName string
Parser func(val string) interface{}
FormatType FormatType
Layout string
}
func NewFormJsonConfig(fieldName string, formatType FormatType) *FormJsonConfig {
return &FormJsonConfig{FieldName: fieldName, FormatType: formatType}
}
func (this *FormJsonConfig) SetLayout(layout string) *FormJsonConfig {
this.Layout = layout
return this
}
func (this *FormJsonConfig) SetParser(parser func(val string) interface{}) *FormJsonConfig {
this.Parser = parser
return this
}
func (this *FormJsonConfig) List() []*FormJsonConfig {
return []*FormJsonConfig{this}
}
type JsonParser struct {
DefaultLocation *time.Location
}
func NewJsonParser() *JsonParser {
return &JsonParser{}
}
func ParseUrlValues[T any](data url.Values, modelOpts ...*T) *optional.Optional[*T] {
var model T
if len(modelOpts) > 0 {
model = *modelOpts[0]
}
parser := NewJsonParser()
values := parser.UrlValuesToMap(data)
jsonData, err := json.Marshal(values)
if err != nil {
return optional.OfFail[*T](err)
}
err = json.Unmarshal(jsonData, &model)
if err != nil {
return optional.OfFail[*T](err)
}
return optional.Of[*T](&model)
}
func (this *JsonParser) JsonToMap(ctx *context.Context) (map[string]interface{}, error) {
return this.JsonBytesToMap(ctx.Input.RequestBody)
}
func (this *JsonParser) JsonBytesToMap(body []byte) (map[string]interface{}, error) {
data := make(map[string]interface{})
err := json.Unmarshal(body, &data)
return data, err
}
func (this *JsonParser) JsonToModel(ctx *context.Context, model interface{}) error {
//fmt.Println("### %s", string(ctx.Input.RequestBody))
err := json.Unmarshal(ctx.Input.RequestBody, &model)
if err != nil {
return errors.New(fmt.Sprintf("error on JsonToModel.json.Unmarshal: %v", err.Error()))
}
return nil
}
func (this *JsonParser) FormJsonToModel(ctx *context.Context, model interface{}) error {
data := this.FormToJsonWithFieldsConfigs(ctx, nil)
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
return json.Unmarshal(jsonData, &model)
}
func (this *JsonParser) FormJsonToModelWithCOnfigs(ctx *context.Context, model interface{}, configs []*FormJsonConfig) error {
data := this.formToJsonWithFieldsConfigs(ctx, nil, configs)
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
return json.Unmarshal(jsonData, &model)
}
func (this *JsonParser) FormToMap(ctx *context.Context, configs ...[]*FormJsonConfig) map[string]interface{} {
if len(configs) > 0 {
return this.FormToJsonWithConfigs(ctx, configs[0])
} else {
return this.FormToJson(ctx)
}
}
func (this *JsonParser) FormToJson(ctx *context.Context) map[string]interface{} {
return this.formToJsonWithFieldsConfigs(ctx, nil, nil)
}
func (this *JsonParser) FormToJsonWithFieldsConfigs(ctx *context.Context, configs map[string]string) map[string]interface{} {
return this.formToJsonWithFieldsConfigs(ctx, configs, nil)
}
func (this *JsonParser) FormToJsonWithConfigs(ctx *context.Context, configs []*FormJsonConfig) map[string]interface{} {
return this.formToJsonWithFieldsConfigs(ctx, nil, configs)
}
func (this *JsonParser) formToJsonWithFieldsConfigs(ctx *context.Context, configsMap map[string]string, configs []*FormJsonConfig) map[string]interface{} {
data := ctx.Request.Form
return this.UrlValuesToMapWithConfigs(data, configsMap, configs)
}
func (this *JsonParser) UrlValuesToMap(data url.Values) map[string]interface{} {
return this.UrlValuesToMapWithConfigs(data, nil, nil)
}
func (this *JsonParser) UrlValuesToMapWithConfigs(data url.Values, configsMap map[string]string, configs []*FormJsonConfig) map[string]interface{} {
jsonMap := make(map[string]interface{})
findConfig := func(fieldName string) *FormJsonConfig {
if configs != nil {
for _, config := range configs {
if config.FieldName == fieldName {
return config
}
}
}
return nil
}
processValue := func(currentConfig *FormJsonConfig, value string) interface{} {
if currentConfig != nil {
if currentConfig.Parser != nil {
return currentConfig.Parser(value)
} else {
switch currentConfig.FormatType {
case FormatTypeFloat:
if strings.Contains(value, ",") && strings.Contains(value, ".") {
if strings.Index(value, ",") < strings.Index(value, ".") {
return strings.Replace(value, ",", "", -1)
}
return strings.Replace(strings.Replace(value, ".", "", -1), ",", ".", -1)
} else if strings.Contains(value, ",") {
return strings.Replace(value, ",", ".", -1)
} else if strings.TrimSpace(value) == "" {
return "0.0"
}
return value
case FormatTypeInt:
if value == "" {
return "0"
}
return value
case FormatTypeDate:
if len(value) > 0 {
auxDate, _ := util.DateParse(currentConfig.Layout, value)
jsonDateLayout := "2006-01-02T15:04:05-07:00"
if !auxDate.IsZero() {
return auxDate.Format(jsonDateLayout)
}
}
return ""
case FormatTypeBool:
return value
}
}
}
return value
}
if configs == nil {
configs = []*FormJsonConfig{}
}
for key, val := range configsMap {
switch val {
case "float":
configs = append(configs, NewFormJsonConfig(key, FormatTypeFloat))
break
case "int":
configs = append(configs, NewFormJsonConfig(key, FormatTypeInt))
break
case "bool":
configs = append(configs, NewFormJsonConfig(key, FormatTypeBool))
break
default:
if strings.Contains(val, "date:") {
configs = append(configs, NewFormJsonConfig(key, FormatTypeDate).SetLayout(strings.Split(val, ":")[1]))
} else {
logs.Error("Invalid format: %v. use [float | int | bool | date:DD/MM/YYYY]", val)
}
break
}
}
for k, v := range data {
if len(v) == 0 {
continue
}
currentConfig := findConfig(k)
if strings.Contains(k, ".") {
keys := strings.Split(k, ".")
parent := jsonMap
for i, key := range keys {
if currentConfig == nil {
currentConfig = findConfig(key)
}
if _, ok := parent[key].(map[string]interface{}); !ok {
parent[key] = make(map[string]interface{})
}
if i < len(keys)-1 {
parent = parent[key].(map[string]interface{})
} else {
parent[key] = v[0]
if parent[key] != nil {
value := parent[key].(string)
if currentConfig != nil {
parent[key] = processValue(currentConfig, value)
} else {
parent[key] = value
}
}
}
}
} else {
//fmt.Println("k = ", k, " value = ", v[0])
value := v[0]
if currentConfig != nil {
jsonMap[k] = processValue(currentConfig, value)
} else {
jsonMap[k] = value
}
}
}
return jsonMap
}
func (this *JsonParser) FormToModel(ctx *context.Context, model interface{}) error {
return this.FormToModelWithFieldsConfigs(ctx, model, nil)
}
func (this *JsonParser) FormToModelWithFieldsConfigs(ctx *context.Context, model interface{}, configs map[string]string) error {
jsonMap := this.FormToJsonWithFieldsConfigs(ctx, configs)
return this.MapToModel(jsonMap, model)
}
func (this *JsonParser) MapToModel(data map[string]interface{}, model interface{}) error {
jsonData, err := json.Marshal(data)
if err != nil {
return errors.New(fmt.Sprintf("error on FormToModel.json.Marshal: %v", err.Error()))
}
err = json.Unmarshal(jsonData, model)
if err != nil {
return errors.New(fmt.Sprintf("error on FormToModel.json.Unmarshal: %v", err.Error()))
}
return nil
}
func (this *JsonParser) StructToModel(data interface{}, model interface{}) error {
jsonData, err := json.Marshal(data)
if err != nil {
return errors.New(fmt.Sprintf("error on FormToModel.json.Marshal: %v", err.Error()))
}
err = json.Unmarshal(jsonData, model)
if err != nil {
return errors.New(fmt.Sprintf("error on FormToModel.json.Unmarshal: %v", err.Error()))
}
return nil
}
func (this *JsonParser) GetJsonObject(json map[string]interface{}, key string) map[string]interface{} {
if this.HasJsonKey(json, key) {
opt, _ := json[key]
if opt != nil {
return opt.(map[string]interface{})
}
}
return nil
}
func (this *JsonParser) GetJsonArray(json map[string]interface{}, key string) []map[string]interface{} {
if this.HasJsonKey(json, key) {
opt, _ := json[key]
items := new([]map[string]interface{})
if array, ok := opt.([]interface{}); ok {
for _, it := range array {
if p, ok := it.(map[string]interface{}); ok {
*items = append(*items, p)
}
}
}
return *items
}
return nil
}
func (this *JsonParser) GetJsonSimpleArray(json map[string]interface{}, key string) []interface{} {
if this.HasJsonKey(json, key) {
opt, _ := json[key]
if array, ok := opt.([]interface{}); ok {
return array
}
}
return nil
}
func (this *JsonParser) GetArrayFromJson(json map[string]interface{}, key string) []interface{} {
if this.HasJsonKey(json, key) {
opt, _ := json[key]
items := new([]interface{})
if array, ok := opt.([]interface{}); ok {
for _, it := range array {
//if p, ok := it.(map[string]interface{}); ok {
*items = append(*items, it)
//}
}
}
return *items
}
return nil
}
func (this *JsonParser) GetJsonInt(json map[string]interface{}, key string) int {
var val int
if this.HasJsonKey(json, key) {
if _, ok := json[key].(int); ok {
val = json[key].(int)
} else if _, ok := json[key].(int64); ok {
val = int(json[key].(int64))
} else if _, ok := json[key].(float64); ok {
val = int(json[key].(float64))
} else if _, ok := json[key].(float32); ok {
val = int(json[key].(float32))
} else {
val, _ = strconv.Atoi(this.GetJsonString(json, key))
}
}
return val
}
func (this *JsonParser) GetJsonInt64(json map[string]interface{}, key string) int64 {
var val int
if this.HasJsonKey(json, key) {
if _, ok := json[key].(int); ok {
val = json[key].(int)
} else if _, ok := json[key].(int64); ok {
val = int(json[key].(int64))
} else if _, ok := json[key].(float64); ok {
val = int(json[key].(float64))
} else if _, ok := json[key].(float32); ok {
val = int(json[key].(float32))
} else {
val, _ = strconv.Atoi(this.GetJsonString(json, key))
}
}
return int64(val)
}
func (this *JsonParser) GetJsonFloat32(json map[string]interface{}, key string) float32 {
var val float32
if this.HasJsonKey(json, key) {
if _, ok := json[key].(float32); ok {
val = json[key].(float32)
} else if _, ok := json[key].(float64); ok {
val = float32(json[key].(float64))
} else if _, ok := json[key].(int64); ok {
val = float32(json[key].(int64))
} else if _, ok := json[key].(int); ok {
val = float32(json[key].(int))
} else {
v, _ := strconv.ParseFloat(this.GetJsonString(json, key), 32)
val = float32(v)
}
}
return float32(val)
}
func (this *JsonParser) GetJsonFloat64(json map[string]interface{}, key string) float64 {
var val float64
if this.HasJsonKey(json, key) {
if _, ok := json[key].(float64); ok {
val = json[key].(float64)
} else if _, ok := json[key].(float32); ok {
val = float64(json[key].(float32))
} else if _, ok := json[key].(int64); ok {
val = float64(json[key].(int64))
} else if _, ok := json[key].(int); ok {
val = float64(json[key].(int))
} else {
v, _ := strconv.ParseFloat(this.GetJsonString(json, key), 64)
val = float64(v)
}
}
return float64(val)
}
func (this *JsonParser) GetJsonBool(json map[string]interface{}, key string) bool {
var val bool
if this.HasJsonKey(json, key) {
if _, ok := json[key].(bool); ok {
val = json[key].(bool)
} else {
val, _ = strconv.ParseBool(this.GetJsonString(json, key))
}
}
return val
}
func (this *JsonParser) GetJsonString(json map[string]interface{}, key string) string {
var val string
if !this.HasJsonKey(json, key) {
return val
}
if _, ok := json[key].(string); ok {
val = json[key].(string)
if val == "null" || val == "undefined" {
return val
}
}
return val
}
func (this *JsonParser) JsonInterfaceToInt64(item interface{}) int64 {
var val int = 0
if _, ok := item.(int); ok {
val = item.(int)
} else if _, ok := item.(int64); ok {
val = int(item.(int64))
} else if _, ok := item.(float64); ok {
val = int(item.(float64))
} else {
val, _ = strconv.Atoi(fmt.Sprintf("%v", item))
}
return int64(val)
}
func (this *JsonParser) GetJsonDate(json map[string]interface{}, key string, layout string) time.Time {
date, _ := time.ParseInLocation(layout, this.GetJsonString(json, key), this.DefaultLocation)
return date
}
func (this *JsonParser) HasJsonKey(json map[string]interface{}, key string) bool {
if _, ok := json[key]; ok {
return true
}
return false
}