-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathjsonq.go
859 lines (771 loc) · 21.2 KB
/
jsonq.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
package gojsonq
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
)
// New returns a new instance of JSONQ
func New(options ...OptionFunc) *JSONQ {
jq := &JSONQ{
queryMap: defaultQueries(),
option: option{
decoder: &DefaultDecoder{},
separator: defaultSeparator,
},
}
for _, option := range options {
if err := option(jq); err != nil {
jq.addError(err)
}
}
return jq
}
// empty represents an empty result
var empty interface{}
const defaultSeparator = "."
// query describes a query
type query struct {
key, operator string
value interface{}
}
// JSONQ describes a JSONQ type which contains all the state
type JSONQ struct {
option option // contains options for JSONQ
queryMap map[string]QueryFunc // contains query functions
node string // contains node name
raw json.RawMessage // raw message from source (reader, string or file)
rootJSONContent interface{} // original decoded json data
jsonContent interface{} // copy of original decoded json data for further processing
queryIndex int // contains number of orWhere query call
queries [][]query // nested queries
attributes []string // select attributes that will be available in final resuls
offsetRecords int // number of records that will be skipped in final result
limitRecords int // number of records that will be available in final result
distinctProperty string // contain the distinct attribute name
errors []error // contains all the errors when processing
}
// String satisfies stringer interface
func (j *JSONQ) String() string {
return fmt.Sprintf("\nContent: %s\nQueries:%v\n", string(j.raw), j.queries)
}
// decode decodes the raw message to Go data structure
func (j *JSONQ) decode() *JSONQ {
err := j.option.decoder.Decode(j.raw, &j.rootJSONContent)
if err != nil {
return j.addError(err)
}
j.jsonContent = j.rootJSONContent
return j
}
// Copy returns a new fresh instance of JSONQ with the original copy of data so that you can do
// concurrent operation on the same data without being decoded again
func (j *JSONQ) Copy() *JSONQ {
tmp := *j
return tmp.reset()
}
// File read the json content from physical file
func (j *JSONQ) File(filename string) *JSONQ {
bb, err := ioutil.ReadFile(filename)
if err != nil {
return j.addError(err)
}
j.raw = bb
return j.decode() // handle error
}
// JSONString reads the json content from valid json string
// Deprecated: this method will remove in next major release
func (j *JSONQ) JSONString(json string) *JSONQ {
return j.FromString(json)
}
// FromString reads the content from valid json/xml/csv/yml string
func (j *JSONQ) FromString(str string) *JSONQ {
j.raw = []byte(str)
return j.decode() // handle error
}
// Reader reads the json content from io reader
func (j *JSONQ) Reader(r io.Reader) *JSONQ {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(r)
if err != nil {
return j.addError(err)
}
j.raw = buf.Bytes()
buf.Reset() // reset the buffer
return j.decode()
}
// Error returns first occurred error
func (j *JSONQ) Error() error {
errsln := len(j.errors)
if errsln == 0 {
return nil
}
return j.errors[0]
}
// Errors returns list of all errors
func (j *JSONQ) Errors() []error {
return j.errors
}
// addError adds error to error list
func (j *JSONQ) addError(err error) *JSONQ {
j.errors = append(j.errors, fmt.Errorf("gojsonq: %v", err))
return j
}
// Macro adds a new query func to the JSONQ
func (j *JSONQ) Macro(operator string, fn QueryFunc) *JSONQ {
if _, ok := j.queryMap[operator]; ok {
j.addError(fmt.Errorf("%s is already registered in query map", operator))
return j
}
j.queryMap[operator] = fn
return j
}
// From seeks the json content to provided node. e.g: "users.[0]" or "users.[0].name"
func (j *JSONQ) From(node string) *JSONQ {
j.node = node
v, err := getNestedValue(j.jsonContent, node, j.option.separator)
if err != nil {
j.addError(err)
}
j.jsonContent = v
return j
}
// FromInterface reads the content from valid map[string]interface{}
func (j *JSONQ) FromInterface(v interface{}) *JSONQ {
switch data := v.(type) {
case []interface{}, map[string]interface{}, map[string][]interface{}:
j.rootJSONContent = data
j.jsonContent = j.rootJSONContent
default:
j.addError(fmt.Errorf("invalid type [%T]", v))
}
return j
}
// Select use for selection of the properties from query result
func (j *JSONQ) Select(properties ...string) *JSONQ {
j.attributes = append(j.attributes, properties...)
return j
}
// Offset skips the number of records in result
func (j *JSONQ) Offset(offset int) *JSONQ {
j.offsetRecords = offset
return j
}
// offset skips the records from result
func (j *JSONQ) offset() *JSONQ {
if list, ok := j.jsonContent.([]interface{}); ok {
if j.offsetRecords < 0 {
j.addError(fmt.Errorf("%d is invalid offset", j.offsetRecords))
return j
}
if len(list) >= j.offsetRecords {
j.jsonContent = list[j.offsetRecords:]
} else {
j.jsonContent = make([]interface{}, 0)
}
}
return j
}
// Limit limits the number of records in result
func (j *JSONQ) Limit(limit int) *JSONQ {
j.limitRecords = limit
return j
}
// limit return the number of records in result set depending on the limit value
func (j *JSONQ) limit() *JSONQ {
if list, ok := j.jsonContent.([]interface{}); ok {
if j.limitRecords <= 0 {
j.addError(fmt.Errorf("%d is invalid limit", j.limitRecords))
return j
}
if len(list) > j.limitRecords {
j.jsonContent = list[:j.limitRecords]
}
}
return j
}
// Where builds a where clause. e.g: Where("name", "contains", "doe")
func (j *JSONQ) Where(key, cond string, val interface{}) *JSONQ {
q := query{
key: key,
operator: cond,
value: val,
}
if j.queryIndex == 0 && len(j.queries) == 0 {
var qq []query
qq = append(qq, q)
j.queries = append(j.queries, qq)
} else {
j.queries[j.queryIndex] = append(j.queries[j.queryIndex], q)
}
return j
}
// WhereEqual is an alias of Where("key", "=", val)
func (j *JSONQ) WhereEqual(key string, val interface{}) *JSONQ {
return j.Where(key, operatorEq, val)
}
// WhereNotEqual is an alias of Where("key", "!=", val)
func (j *JSONQ) WhereNotEqual(key string, val interface{}) *JSONQ {
return j.Where(key, operatorNotEq, val)
}
// WhereNil is an alias of Where("key", "=", nil)
func (j *JSONQ) WhereNil(key string) *JSONQ {
return j.Where(key, operatorEq, nil)
}
// WhereNotNil is an alias of Where("key", "!=", nil)
func (j *JSONQ) WhereNotNil(key string) *JSONQ {
return j.Where(key, operatorNotEq, nil)
}
// WhereIn is an alias for where("key", "in", []string{"a", "b"})
func (j *JSONQ) WhereIn(key string, val interface{}) *JSONQ {
j.Where(key, operatorIn, val)
return j
}
// WhereNotIn is an alias for where("key", "notIn", []string{"a", "b"})
func (j *JSONQ) WhereNotIn(key string, val interface{}) *JSONQ {
j.Where(key, operatorNotIn, val)
return j
}
// OrWhere builds an OrWhere clause, basically it's a group of AND clauses
func (j *JSONQ) OrWhere(key, cond string, val interface{}) *JSONQ {
j.queryIndex++
var qq []query
qq = append(qq, query{
key: key,
operator: cond,
value: val,
})
j.queries = append(j.queries, qq)
return j
}
// WhereStartsWith satisfies Where clause which starts with provided value(string)
func (j *JSONQ) WhereStartsWith(key string, val interface{}) *JSONQ {
return j.Where(key, operatorStartsWith, val)
}
// WhereEndsWith satisfies Where clause which ends with provided value(string)
func (j *JSONQ) WhereEndsWith(key string, val interface{}) *JSONQ {
return j.Where(key, operatorEndsWith, val)
}
// WhereContains satisfies Where clause which contains provided value(string)
func (j *JSONQ) WhereContains(key string, val interface{}) *JSONQ {
return j.Where(key, operatorContains, val)
}
// WhereStrictContains satisfies Where clause which contains provided value(string).
// This is case sensitive
func (j *JSONQ) WhereStrictContains(key string, val interface{}) *JSONQ {
return j.Where(key, operatorStrictContains, val)
}
// WhereLenEqual is an alias of Where("key", "leneq", val)
func (j *JSONQ) WhereLenEqual(key string, val interface{}) *JSONQ {
return j.Where(key, operatorLenEq, val)
}
// WhereLenNotEqual is an alias of Where("key", "lenneq", val)
func (j *JSONQ) WhereLenNotEqual(key string, val interface{}) *JSONQ {
return j.Where(key, operatorLenNotEq, val)
}
// findInArray traverses through a list and returns the value list.
// This helps to process Where/OrWhere queries
func (j *JSONQ) findInArray(aa []interface{}) []interface{} {
result := make([]interface{}, 0)
for _, a := range aa {
if m, ok := a.(map[string]interface{}); ok {
result = append(result, j.findInMap(m)...)
}
}
return result
}
// findInMap traverses through a map and returns the matched value list.
// This helps to process Where/OrWhere queries
func (j *JSONQ) findInMap(vm map[string]interface{}) []interface{} {
result := make([]interface{}, 0)
orPassed := false
for _, qList := range j.queries {
andPassed := true
for _, q := range qList {
cf, ok := j.queryMap[q.operator]
if !ok {
j.addError(fmt.Errorf("invalid operator %s", q.operator))
return result
}
nv, errnv := getNestedValue(vm, q.key, j.option.separator)
if errnv != nil {
j.addError(errnv)
andPassed = false
} else {
qb, err := cf(nv, q.value)
if err != nil {
j.addError(err)
}
andPassed = andPassed && qb
}
}
orPassed = orPassed || andPassed
}
if orPassed {
result = append(result, vm)
}
return result
}
// processQuery makes the result
func (j *JSONQ) processQuery() *JSONQ {
if aa, ok := j.jsonContent.([]interface{}); ok {
j.jsonContent = j.findInArray(aa)
}
return j
}
// prepare builds the queries
func (j *JSONQ) prepare() *JSONQ {
if len(j.queries) > 0 {
j.processQuery()
}
if j.distinctProperty != "" {
j.distinct()
}
if len(j.attributes) > 0 {
j.jsonContent = j.only(j.attributes...)
}
j.queryIndex = 0
return j
}
// GroupBy builds a chunk of exact matched data in a group list using provided attribute/column/property
func (j *JSONQ) GroupBy(property string) *JSONQ {
j.prepare()
dt := map[string][]interface{}{}
if aa, ok := j.jsonContent.([]interface{}); ok {
for _, a := range aa {
if vm, ok := a.(map[string]interface{}); ok {
v, err := getNestedValue(vm, property, j.option.separator)
if err != nil {
j.addError(err)
} else {
dt[toString(v)] = append(dt[toString(v)], vm)
}
}
}
}
// replace the new result with the previous result
j.jsonContent = dt
return j
}
// Sort sorts an array
// default ascending order, pass "desc" for descending order
func (j *JSONQ) Sort(order ...string) *JSONQ {
j.prepare()
asc := true
if len(order) > 1 {
return j.addError(fmt.Errorf("sort accepts only one argument asc/desc"))
}
if len(order) > 0 && order[0] == "desc" {
asc = false
}
if arr, ok := j.jsonContent.([]interface{}); ok {
j.jsonContent = sortList(arr, asc)
}
return j
}
// SortBy sorts an array
// default ascending order, pass "desc" for descending order
func (j *JSONQ) SortBy(order ...string) *JSONQ {
j.prepare()
asc := true
if len(order) == 0 {
return j.addError(fmt.Errorf("provide at least one argument as property name"))
}
if len(order) > 2 {
return j.addError(fmt.Errorf("sort accepts only two arguments. first argument property name and second argument asc/desc"))
}
if len(order) > 1 && order[1] == "desc" {
asc = false
}
return j.sortBy(order[0], asc)
}
// Distinct builds distinct value using provided attribute/column/property
func (j *JSONQ) Distinct(property string) *JSONQ {
j.distinctProperty = property
return j
}
// distinct builds distinct value using provided attribute/column/property
func (j *JSONQ) distinct() *JSONQ {
m := map[string]bool{}
var dt = make([]interface{}, 0)
if aa, ok := j.jsonContent.([]interface{}); ok {
for _, a := range aa {
if vm, ok := a.(map[string]interface{}); ok {
v, err := getNestedValue(vm, j.distinctProperty, j.option.separator)
if err != nil {
j.addError(err)
} else {
if _, exist := m[toString(v)]; !exist {
dt = append(dt, vm)
m[toString(v)] = true
}
}
}
}
}
// replace the new result with the previous result
j.jsonContent = dt
return j
}
// sortBy sorts list of map
func (j *JSONQ) sortBy(property string, asc bool) *JSONQ {
sortResult, ok := j.jsonContent.([]interface{})
if !ok {
return j
}
if len(sortResult) == 0 {
return j
}
sm := &sortMap{}
sm.separator = j.option.separator
sm.key = property
if !asc {
sm.desc = true
}
sm.Sort(sortResult)
for _, e := range sm.errs {
j.addError(e)
}
// replace the new result with the previous result
j.jsonContent = sortResult
return j
}
// only return selected properties in result
func (j *JSONQ) only(properties ...string) interface{} {
var result = make([]interface{}, 0)
if aa, ok := j.jsonContent.([]interface{}); ok {
for _, am := range aa {
tmap := map[string]interface{}{}
for _, prop := range properties {
node, alias := makeAlias(prop, j.option.separator)
rv, errV := getNestedValue(am, node, j.option.separator)
if errV != nil {
j.addError(errV)
continue
}
tmap[alias] = rv
}
if len(tmap) > 0 {
result = append(result, tmap)
}
}
}
return result
}
// Only collects the properties from a list of object
func (j *JSONQ) Only(properties ...string) interface{} {
return j.prepare().only(properties...)
}
// OnlyR collects the properties from a list of object and return as Result instance
func (j *JSONQ) OnlyR(properties ...string) (*Result, error) {
v := j.Only(properties...)
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// Pluck build an array of values form a property of a list of objects
func (j *JSONQ) Pluck(property string) interface{} {
j.prepare()
if j.distinctProperty != "" {
j.distinct()
}
if j.limitRecords != 0 {
j.limit()
}
var result = make([]interface{}, 0)
if aa, ok := j.jsonContent.([]interface{}); ok {
for _, am := range aa {
if mv, ok := am.(map[string]interface{}); ok {
if v, ok := mv[property]; ok {
result = append(result, v)
}
}
}
}
return result
}
// PluckR build an array of values form a property of a list of objects and return as Result instance
func (j *JSONQ) PluckR(property string) (*Result, error) {
v := j.Pluck(property)
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// reset resets the current state of JSONQ instance
func (j *JSONQ) reset() *JSONQ {
j.raw = nil
j.jsonContent = j.rootJSONContent
j.node = ""
j.queries = make([][]query, 0)
j.attributes = make([]string, 0)
j.queryIndex = 0
j.offsetRecords = 0
j.limitRecords = 0
j.distinctProperty = ""
j.errors = make([]error, 0)
return j
}
// Reset resets the current state of JSON instance and make a fresh object with the original json content
func (j *JSONQ) Reset() *JSONQ {
return j.reset()
}
// Get return the result
func (j *JSONQ) Get() interface{} {
j.prepare()
if j.offsetRecords != 0 {
j.offset()
}
if j.limitRecords != 0 {
j.limit()
}
return j.jsonContent
}
// GetR return the query results as Result instance
func (j *JSONQ) GetR() (*Result, error) {
v := j.Get()
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// First returns the first element of a list
func (j *JSONQ) First() interface{} {
j.prepare()
if arr, ok := j.jsonContent.([]interface{}); ok {
if len(arr) > 0 {
return arr[0]
}
}
return empty
}
// FirstR returns the first element of a list as Result instance
func (j *JSONQ) FirstR() (*Result, error) {
v := j.First()
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// Last returns the last element of a list
func (j *JSONQ) Last() interface{} {
j.prepare()
if arr, ok := j.jsonContent.([]interface{}); ok {
if l := len(arr); l > 0 {
return arr[l-1]
}
}
return empty
}
// LastR returns the last element of a list as Result instance
func (j *JSONQ) LastR() (*Result, error) {
v := j.Last()
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// Nth returns the nth element of a list
func (j *JSONQ) Nth(index int) interface{} {
if index == 0 {
j.addError(fmt.Errorf("index is not zero based"))
return empty
}
j.prepare()
if arr, ok := j.jsonContent.([]interface{}); ok {
alen := len(arr)
if alen == 0 {
j.addError(fmt.Errorf("list is empty"))
return empty
}
if abs(index) > alen {
j.addError(fmt.Errorf("index out of range"))
return empty
}
if index > 0 {
return arr[index-1]
}
return arr[alen+index]
}
return empty
}
// NthR returns the nth element of a list as Result instance
func (j *JSONQ) NthR(index int) (*Result, error) {
v := j.Nth(index)
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// Find returns the result of a exact matching path
func (j *JSONQ) Find(path string) interface{} {
return j.From(path).Get()
}
// FindR returns the result as Result instance from the exact matching path
func (j *JSONQ) FindR(path string) (*Result, error) {
v := j.Find(path)
if err := j.Error(); err != nil {
return nil, err
}
return NewResult(v), nil
}
// Count returns the number of total items.
// This could be a length of list/array/map
func (j *JSONQ) Count() int {
j.prepare()
var lnth int
// list of items
if list, ok := j.jsonContent.([]interface{}); ok {
lnth = len(list)
}
// return map len // TODO: need to think about map
if m, ok := j.jsonContent.(map[string]interface{}); ok {
lnth = len(m)
}
// group data items
if m, ok := j.jsonContent.(map[string][]interface{}); ok {
lnth = len(m)
}
return lnth
}
// Out write the queried data to defined custom type
func (j *JSONQ) Out(v interface{}) {
data, err := json.Marshal(j.Get())
if err != nil {
j.addError(err)
return
}
if err := json.Unmarshal(data, &v); err != nil {
j.addError(err)
}
}
// Writer write the queried data to a io.Writer
func (j *JSONQ) Writer(w io.Writer) {
err := json.NewEncoder(w).Encode(j.Get())
if err != nil {
j.addError(err)
return
}
}
// More provides the functionality to query over the resultant data. See https://github.com/thedevsaddam/gojsonq/wiki/Queries#More
func (j *JSONQ) More() *JSONQ {
j.raw = nil
j.rootJSONContent = j.Get()
j.node = ""
j.queries = make([][]query, 0)
j.attributes = make([]string, 0)
j.queryIndex = 0
j.limitRecords = 0
j.distinctProperty = ""
return j
}
// getFloatValFromArray returns a list of float64 values from array/map for aggregation
func (j *JSONQ) getFloatValFromArray(arr []interface{}, property ...string) []float64 {
var ff []float64
for _, a := range arr {
if av, ok := a.(float64); ok {
if len(property) > 0 {
j.addError(fmt.Errorf("unnecessary property name for array"))
return nil
}
ff = append(ff, av)
}
if mv, ok := a.(map[string]interface{}); ok {
if len(property) == 0 {
j.addError(fmt.Errorf("property name can not be empty for object"))
return nil
}
if fi, ok := mv[property[0]]; ok {
if flt, ok := fi.(float64); ok {
ff = append(ff, flt)
} else {
j.addError(fmt.Errorf("property %s's value '%v' is not numeric", property[0], fi))
return nil
}
} else {
j.addError(fmt.Errorf("property '%s' does not exist", property[0]))
return nil
}
}
}
return ff
}
// getAggregationValues returns a list of float64 values for aggregation
func (j *JSONQ) getAggregationValues(property ...string) []float64 {
j.prepare()
if j.distinctProperty != "" {
j.distinct()
}
if j.limitRecords != 0 {
j.limit()
}
var ff []float64
if arr, ok := j.jsonContent.([]interface{}); ok {
ff = j.getFloatValFromArray(arr, property...)
}
if mv, ok := j.jsonContent.(map[string]interface{}); ok {
if len(property) == 0 {
j.addError(fmt.Errorf("property can not be empty for object"))
return nil
}
if fi, ok := mv[property[0]]; ok {
if flt, ok := fi.(float64); ok {
ff = append(ff, flt)
} else {
j.addError(fmt.Errorf("property %s's value '%v' is not numeric", property[0], fi))
return nil
}
} else {
j.addError(fmt.Errorf("property '%s' does not exist", property[0]))
return nil
}
}
return ff
}
// Sum returns sum of values from array or from map using property
func (j *JSONQ) Sum(property ...string) float64 {
var sum float64
for _, flt := range j.getAggregationValues(property...) {
sum += flt
}
return sum
}
// Avg returns average of values from array or from map using property
func (j *JSONQ) Avg(property ...string) float64 {
var sum float64
fl := j.getAggregationValues(property...)
for _, flt := range fl {
sum += flt
}
return sum / float64(len(fl))
}
// Min returns minimum value from array or from map using property
func (j *JSONQ) Min(property ...string) float64 {
var min float64
flist := j.getAggregationValues(property...)
if len(flist) > 0 {
min = flist[0]
}
for _, flt := range flist {
if flt < min {
min = flt
}
}
return min
}
// Max returns maximum value from array or from map using property
func (j *JSONQ) Max(property ...string) float64 {
var max float64
flist := j.getAggregationValues(property...)
if len(flist) > 0 {
max = flist[0]
}
for _, flt := range flist {
if flt > max {
max = flt
}
}
return max
}