Debian Codegraph @

jsonq.go

raw symbols SCIP
1 package gojsonq
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 )
10
11 // New returns a new instance of JSONQ
12 func New(options ...OptionFunc) *JSONQ {
13 jq := &JSONQ{
14 queryMap: defaultQueries(),
15 option: option{
16 decoder: &DefaultDecoder{},
17 separator: defaultSeparator,
18 },
19 }
20 for _, option := range options {
21 if err := option(jq); err != nil {
22 jq.addError(err)
23 }
24 }
25 return jq
26 }
27
28 // empty represents an empty result
29 var empty interface{}
30
31 const defaultSeparator = "."
32
33 // query describes a query
34 type query struct {
35 key, operator string
36 value interface{}
37 }
38
39 // JSONQ describes a JSONQ type which contains all the state
40 type JSONQ struct {
41 option option // contains options for JSONQ
42 queryMap map[string]QueryFunc // contains query functions
43 node string // contains node name
44 raw json.RawMessage // raw message from source (reader, string or file)
45 rootJSONContent interface{} // original decoded json data
46 jsonContent interface{} // copy of original decoded json data for further processing
47 queryIndex int // contains number of orWhere query call
48 queries [][]query // nested queries
49 attributes []string // select attributes that will be available in final resuls
50 offsetRecords int // number of records that will be skipped in final result
51 limitRecords int // number of records that will be available in final result
52 distinctProperty string // contain the distinct attribute name
53 errors []error // contains all the errors when processing
54 }
55
56 // String satisfies stringer interface
57 func (j *JSONQ) String() string {
58 return fmt.Sprintf("\nContent: %s\nQueries:%v\n", string(j.raw), j.queries)
59 }
60
61 // decode decodes the raw message to Go data structure
62 func (j *JSONQ) decode() *JSONQ {
63 err := j.option.decoder.Decode(j.raw, &j.rootJSONContent)
64 if err != nil {
65 return j.addError(err)
66 }
67 j.jsonContent = j.rootJSONContent
68 return j
69 }
70
71 // Copy returns a new fresh instance of JSONQ with the original copy of data so that you can do
72 // concurrent operation on the same data without being decoded again
73 func (j *JSONQ) Copy() *JSONQ {
74 tmp := *j
75 return tmp.reset()
76 }
77
78 // File read the json content from physical file
79 func (j *JSONQ) File(filename string) *JSONQ {
80 bb, err := ioutil.ReadFile(filename)
81 if err != nil {
82 return j.addError(err)
83 }
84 j.raw = bb
85 return j.decode() // handle error
86 }
87
88 // JSONString reads the json content from valid json string
89 // Deprecated: this method will remove in next major release
90 func (j *JSONQ) JSONString(json string) *JSONQ {
91 return j.FromString(json)
92 }
93
94 // FromString reads the content from valid json/xml/csv/yml string
95 func (j *JSONQ) FromString(str string) *JSONQ {
96 j.raw = []byte(str)
97 return j.decode() // handle error
98 }
99
100 // Reader reads the json content from io reader
101 func (j *JSONQ) Reader(r io.Reader) *JSONQ {
102 buf := new(bytes.Buffer)
103 _, err := buf.ReadFrom(r)
104 if err != nil {
105 return j.addError(err)
106 }
107 j.raw = buf.Bytes()
108 buf.Reset() // reset the buffer
109 return j.decode()
110 }
111
112 // Error returns first occurred error
113 func (j *JSONQ) Error() error {
114 errsln := len(j.errors)
115 if errsln == 0 {
116 return nil
117 }
118 return j.errors[0]
119 }
120
121 // Errors returns list of all errors
122 func (j *JSONQ) Errors() []error {
123 return j.errors
124 }
125
126 // addError adds error to error list
127 func (j *JSONQ) addError(err error) *JSONQ {
128 j.errors = append(j.errors, fmt.Errorf("gojsonq: %v", err))
129 return j
130 }
131
132 // Macro adds a new query func to the JSONQ
133 func (j *JSONQ) Macro(operator string, fn QueryFunc) *JSONQ {
134 if _, ok := j.queryMap[operator]; ok {
135 j.addError(fmt.Errorf("%s is already registered in query map", operator))
136 return j
137 }
138 j.queryMap[operator] = fn
139 return j
140 }
141
142 // From seeks the json content to provided node. e.g: "users.[0]" or "users.[0].name"
143 func (j *JSONQ) From(node string) *JSONQ {
144 j.node = node
145 v, err := getNestedValue(j.jsonContent, node, j.option.separator)
146 if err != nil {
147 j.addError(err)
148 }
149 j.jsonContent = v
150 return j
151 }
152
153 // FromInterface reads the content from valid map[string]interface{}
154 func (j *JSONQ) FromInterface(v interface{}) *JSONQ {
155 switch data := v.(type) {
156 case []interface{}, map[string]interface{}, map[string][]interface{}:
157 j.rootJSONContent = data
158 j.jsonContent = j.rootJSONContent
159 default:
160 j.addError(fmt.Errorf("invalid type [%T]", v))
161 }
162 return j
163 }
164
165 // Select use for selection of the properties from query result
166 func (j *JSONQ) Select(properties ...string) *JSONQ {
167 j.attributes = append(j.attributes, properties...)
168 return j
169 }
170
171 // Offset skips the number of records in result
172 func (j *JSONQ) Offset(offset int) *JSONQ {
173 j.offsetRecords = offset
174 return j
175 }
176
177 // offset skips the records from result
178 func (j *JSONQ) offset() *JSONQ {
179 if list, ok := j.jsonContent.([]interface{}); ok {
180 if j.offsetRecords < 0 {
181 j.addError(fmt.Errorf("%d is invalid offset", j.offsetRecords))
182 return j
183 }
184 if len(list) >= j.offsetRecords {
185 j.jsonContent = list[j.offsetRecords:]
186 } else {
187 j.jsonContent = make([]interface{}, 0)
188 }
189 }
190 return j
191 }
192
193 // Limit limits the number of records in result
194 func (j *JSONQ) Limit(limit int) *JSONQ {
195 j.limitRecords = limit
196 return j
197 }
198
199 // limit return the number of records in result set depending on the limit value
200 func (j *JSONQ) limit() *JSONQ {
201 if list, ok := j.jsonContent.([]interface{}); ok {
202 if j.limitRecords <= 0 {
203 j.addError(fmt.Errorf("%d is invalid limit", j.limitRecords))
204 return j
205 }
206 if len(list) > j.limitRecords {
207 j.jsonContent = list[:j.limitRecords]
208 }
209 }
210 return j
211 }
212
213 // Where builds a where clause. e.g: Where("name", "contains", "doe")
214 func (j *JSONQ) Where(key, cond string, val interface{}) *JSONQ {
215 q := query{
216 key: key,
217 operator: cond,
218 value: val,
219 }
220 if j.queryIndex == 0 && len(j.queries) == 0 {
221 var qq []query
222 qq = append(qq, q)
223 j.queries = append(j.queries, qq)
224 } else {
225 j.queries[j.queryIndex] = append(j.queries[j.queryIndex], q)
226 }
227
228 return j
229 }
230
231 // WhereEqual is an alias of Where("key", "=", val)
232 func (j *JSONQ) WhereEqual(key string, val interface{}) *JSONQ {
233 return j.Where(key, operatorEq, val)
234 }
235
236 // WhereNotEqual is an alias of Where("key", "!=", val)
237 func (j *JSONQ) WhereNotEqual(key string, val interface{}) *JSONQ {
238 return j.Where(key, operatorNotEq, val)
239 }
240
241 // WhereNil is an alias of Where("key", "=", nil)
242 func (j *JSONQ) WhereNil(key string) *JSONQ {
243 return j.Where(key, operatorEq, nil)
244 }
245
246 // WhereNotNil is an alias of Where("key", "!=", nil)
247 func (j *JSONQ) WhereNotNil(key string) *JSONQ {
248 return j.Where(key, operatorNotEq, nil)
249 }
250
251 // WhereIn is an alias for where("key", "in", []string{"a", "b"})
252 func (j *JSONQ) WhereIn(key string, val interface{}) *JSONQ {
253 j.Where(key, operatorIn, val)
254 return j
255 }
256
257 // WhereNotIn is an alias for where("key", "notIn", []string{"a", "b"})
258 func (j *JSONQ) WhereNotIn(key string, val interface{}) *JSONQ {
259 j.Where(key, operatorNotIn, val)
260 return j
261 }
262
263 // OrWhere builds an OrWhere clause, basically it's a group of AND clauses
264 func (j *JSONQ) OrWhere(key, cond string, val interface{}) *JSONQ {
265 j.queryIndex++
266 var qq []query
267 qq = append(qq, query{
268 key: key,
269 operator: cond,
270 value: val,
271 })
272 j.queries = append(j.queries, qq)
273 return j
274 }
275
276 // WhereStartsWith satisfies Where clause which starts with provided value(string)
277 func (j *JSONQ) WhereStartsWith(key string, val interface{}) *JSONQ {
278 return j.Where(key, operatorStartsWith, val)
279 }
280
281 // WhereEndsWith satisfies Where clause which ends with provided value(string)
282 func (j *JSONQ) WhereEndsWith(key string, val interface{}) *JSONQ {
283 return j.Where(key, operatorEndsWith, val)
284 }
285
286 // WhereContains satisfies Where clause which contains provided value(string)
287 func (j *JSONQ) WhereContains(key string, val interface{}) *JSONQ {
288 return j.Where(key, operatorContains, val)
289 }
290
291 // WhereStrictContains satisfies Where clause which contains provided value(string).
292 // This is case sensitive
293 func (j *JSONQ) WhereStrictContains(key string, val interface{}) *JSONQ {
294 return j.Where(key, operatorStrictContains, val)
295 }
296
297 // WhereLenEqual is an alias of Where("key", "leneq", val)
298 func (j *JSONQ) WhereLenEqual(key string, val interface{}) *JSONQ {
299 return j.Where(key, operatorLenEq, val)
300 }
301
302 // WhereLenNotEqual is an alias of Where("key", "lenneq", val)
303 func (j *JSONQ) WhereLenNotEqual(key string, val interface{}) *JSONQ {
304 return j.Where(key, operatorLenNotEq, val)
305 }
306
307 // findInArray traverses through a list and returns the value list.
308 // This helps to process Where/OrWhere queries
309 func (j *JSONQ) findInArray(aa []interface{}) []interface{} {
310 result := make([]interface{}, 0)
311 for _, a := range aa {
312 if m, ok := a.(map[string]interface{}); ok {
313 result = append(result, j.findInMap(m)...)
314 }
315 }
316 return result
317 }
318
319 // findInMap traverses through a map and returns the matched value list.
320 // This helps to process Where/OrWhere queries
321 func (j *JSONQ) findInMap(vm map[string]interface{}) []interface{} {
322 result := make([]interface{}, 0)
323 orPassed := false
324 for _, qList := range j.queries {
325 andPassed := true
326 for _, q := range qList {
327 cf, ok := j.queryMap[q.operator]
328 if !ok {
329 j.addError(fmt.Errorf("invalid operator %s", q.operator))
330 return result
331 }
332 nv, errnv := getNestedValue(vm, q.key, j.option.separator)
333 if errnv != nil {
334 j.addError(errnv)
335 andPassed = false
336 } else {
337 qb, err := cf(nv, q.value)
338 if err != nil {
339 j.addError(err)
340 }
341 andPassed = andPassed && qb
342 }
343 }
344 orPassed = orPassed || andPassed
345 }
346 if orPassed {
347 result = append(result, vm)
348 }
349 return result
350 }
351
352 // processQuery makes the result
353 func (j *JSONQ) processQuery() *JSONQ {
354 if aa, ok := j.jsonContent.([]interface{}); ok {
355 j.jsonContent = j.findInArray(aa)
356 }
357 return j
358 }
359
360 // prepare builds the queries
361 func (j *JSONQ) prepare() *JSONQ {
362 if len(j.queries) > 0 {
363 j.processQuery()
364 }
365 if j.distinctProperty != "" {
366 j.distinct()
367 }
368 if len(j.attributes) > 0 {
369 j.jsonContent = j.only(j.attributes...)
370 }
371 j.queryIndex = 0
372 return j
373 }
374
375 // GroupBy builds a chunk of exact matched data in a group list using provided attribute/column/property
376 func (j *JSONQ) GroupBy(property string) *JSONQ {
377 j.prepare()
378
379 dt := map[string][]interface{}{}
380 if aa, ok := j.jsonContent.([]interface{}); ok {
381 for _, a := range aa {
382 if vm, ok := a.(map[string]interface{}); ok {
383 v, err := getNestedValue(vm, property, j.option.separator)
384 if err != nil {
385 j.addError(err)
386 } else {
387 dt[toString(v)] = append(dt[toString(v)], vm)
388 }
389 }
390 }
391 }
392 // replace the new result with the previous result
393 j.jsonContent = dt
394 return j
395 }
396
397 // Sort sorts an array
398 // default ascending order, pass "desc" for descending order
399 func (j *JSONQ) Sort(order ...string) *JSONQ {
400 j.prepare()
401
402 asc := true
403 if len(order) > 1 {
404 return j.addError(fmt.Errorf("sort accepts only one argument asc/desc"))
405 }
406 if len(order) > 0 && order[0] == "desc" {
407 asc = false
408 }
409 if arr, ok := j.jsonContent.([]interface{}); ok {
410 j.jsonContent = sortList(arr, asc)
411 }
412 return j
413 }
414
415 // SortBy sorts an array
416 // default ascending order, pass "desc" for descending order
417 func (j *JSONQ) SortBy(order ...string) *JSONQ {
418 j.prepare()
419 asc := true
420 if len(order) == 0 {
421 return j.addError(fmt.Errorf("provide at least one argument as property name"))
422 }
423 if len(order) > 2 {
424 return j.addError(fmt.Errorf("sort accepts only two arguments. first argument property name and second argument asc/desc"))
425 }
426
427 if len(order) > 1 && order[1] == "desc" {
428 asc = false
429 }
430
431 return j.sortBy(order[0], asc)
432 }
433
434 // Distinct builds distinct value using provided attribute/column/property
435 func (j *JSONQ) Distinct(property string) *JSONQ {
436 j.distinctProperty = property
437 return j
438 }
439
440 // distinct builds distinct value using provided attribute/column/property
441 func (j *JSONQ) distinct() *JSONQ {
442 m := map[string]bool{}
443 var dt = make([]interface{}, 0)
444 if aa, ok := j.jsonContent.([]interface{}); ok {
445 for _, a := range aa {
446 if vm, ok := a.(map[string]interface{}); ok {
447 v, err := getNestedValue(vm, j.distinctProperty, j.option.separator)
448 if err != nil {
449 j.addError(err)
450 } else {
451 if _, exist := m[toString(v)]; !exist {
452 dt = append(dt, vm)
453 m[toString(v)] = true
454 }
455 }
456 }
457 }
458 }
459 // replace the new result with the previous result
460 j.jsonContent = dt
461 return j
462 }
463
464 // sortBy sorts list of map
465 func (j *JSONQ) sortBy(property string, asc bool) *JSONQ {
466 sortResult, ok := j.jsonContent.([]interface{})
467 if !ok {
468 return j
469 }
470 if len(sortResult) == 0 {
471 return j
472 }
473
474 sm := &sortMap{}
475 sm.separator = j.option.separator
476 sm.key = property
477 if !asc {
478 sm.desc = true
479 }
480 sm.Sort(sortResult)
481
482 for _, e := range sm.errs {
483 j.addError(e)
484 }
485
486 // replace the new result with the previous result
487 j.jsonContent = sortResult
488 return j
489 }
490
491 // only return selected properties in result
492 func (j *JSONQ) only(properties ...string) interface{} {
493 var result = make([]interface{}, 0)
494 if aa, ok := j.jsonContent.([]interface{}); ok {
495 for _, am := range aa {
496 tmap := map[string]interface{}{}
497 for _, prop := range properties {
498 node, alias := makeAlias(prop, j.option.separator)
499 rv, errV := getNestedValue(am, node, j.option.separator)
500 if errV != nil {
501 j.addError(errV)
502 continue
503 }
504 tmap[alias] = rv
505 }
506 if len(tmap) > 0 {
507 result = append(result, tmap)
508 }
509 }
510 }
511 return result
512 }
513
514 // Only collects the properties from a list of object
515 func (j *JSONQ) Only(properties ...string) interface{} {
516 return j.prepare().only(properties...)
517 }
518
519 // OnlyR collects the properties from a list of object and return as Result instance
520 func (j *JSONQ) OnlyR(properties ...string) (*Result, error) {
521 v := j.Only(properties...)
522 if err := j.Error(); err != nil {
523 return nil, err
524 }
525 return NewResult(v), nil
526 }
527
528 // Pluck build an array of values form a property of a list of objects
529 func (j *JSONQ) Pluck(property string) interface{} {
530 j.prepare()
531 if j.distinctProperty != "" {
532 j.distinct()
533 }
534 if j.limitRecords != 0 {
535 j.limit()
536 }
537 var result = make([]interface{}, 0)
538 if aa, ok := j.jsonContent.([]interface{}); ok {
539 for _, am := range aa {
540 if mv, ok := am.(map[string]interface{}); ok {
541 if v, ok := mv[property]; ok {
542 result = append(result, v)
543 }
544 }
545 }
546 }
547 return result
548 }
549
550 // PluckR build an array of values form a property of a list of objects and return as Result instance
551 func (j *JSONQ) PluckR(property string) (*Result, error) {
552 v := j.Pluck(property)
553 if err := j.Error(); err != nil {
554 return nil, err
555 }
556 return NewResult(v), nil
557 }
558
559 // reset resets the current state of JSONQ instance
560 func (j *JSONQ) reset() *JSONQ {
561 j.raw = nil
562 j.jsonContent = j.rootJSONContent
563 j.node = ""
564 j.queries = make([][]query, 0)
565 j.attributes = make([]string, 0)
566 j.queryIndex = 0
567 j.offsetRecords = 0
568 j.limitRecords = 0
569 j.distinctProperty = ""
570 j.errors = make([]error, 0)
571 return j
572 }
573
574 // Reset resets the current state of JSON instance and make a fresh object with the original json content
575 func (j *JSONQ) Reset() *JSONQ {
576 return j.reset()
577 }
578
579 // Get return the result
580 func (j *JSONQ) Get() interface{} {
581 j.prepare()
582 if j.offsetRecords != 0 {
583 j.offset()
584 }
585 if j.limitRecords != 0 {
586 j.limit()
587 }
588 return j.jsonContent
589 }
590
591 // GetR return the query results as Result instance
592 func (j *JSONQ) GetR() (*Result, error) {
593 v := j.Get()
594 if err := j.Error(); err != nil {
595 return nil, err
596 }
597 return NewResult(v), nil
598 }
599
600 // First returns the first element of a list
601 func (j *JSONQ) First() interface{} {
602 j.prepare()
603 if arr, ok := j.jsonContent.([]interface{}); ok {
604 if len(arr) > 0 {
605 return arr[0]
606 }
607 }
608 return empty
609 }
610
611 // FirstR returns the first element of a list as Result instance
612 func (j *JSONQ) FirstR() (*Result, error) {
613 v := j.First()
614 if err := j.Error(); err != nil {
615 return nil, err
616 }
617 return NewResult(v), nil
618 }
619
620 // Last returns the last element of a list
621 func (j *JSONQ) Last() interface{} {
622 j.prepare()
623 if arr, ok := j.jsonContent.([]interface{}); ok {
624 if l := len(arr); l > 0 {
625 return arr[l-1]
626 }
627 }
628 return empty
629 }
630
631 // LastR returns the last element of a list as Result instance
632 func (j *JSONQ) LastR() (*Result, error) {
633 v := j.Last()
634 if err := j.Error(); err != nil {
635 return nil, err
636 }
637 return NewResult(v), nil
638 }
639
640 // Nth returns the nth element of a list
641 func (j *JSONQ) Nth(index int) interface{} {
642 if index == 0 {
643 j.addError(fmt.Errorf("index is not zero based"))
644 return empty
645 }
646
647 j.prepare()
648 if arr, ok := j.jsonContent.([]interface{}); ok {
649 alen := len(arr)
650 if alen == 0 {
651 j.addError(fmt.Errorf("list is empty"))
652 return empty
653 }
654 if abs(index) > alen {
655 j.addError(fmt.Errorf("index out of range"))
656 return empty
657 }
658 if index > 0 {
659 return arr[index-1]
660 }
661 return arr[alen+index]
662 }
663 return empty
664 }
665
666 // NthR returns the nth element of a list as Result instance
667 func (j *JSONQ) NthR(index int) (*Result, error) {
668 v := j.Nth(index)
669 if err := j.Error(); err != nil {
670 return nil, err
671 }
672 return NewResult(v), nil
673 }
674
675 // Find returns the result of a exact matching path
676 func (j *JSONQ) Find(path string) interface{} {
677 return j.From(path).Get()
678 }
679
680 // FindR returns the result as Result instance from the exact matching path
681 func (j *JSONQ) FindR(path string) (*Result, error) {
682 v := j.Find(path)
683 if err := j.Error(); err != nil {
684 return nil, err
685 }
686 return NewResult(v), nil
687 }
688
689 // Count returns the number of total items.
690 // This could be a length of list/array/map
691 func (j *JSONQ) Count() int {
692 j.prepare()
693 var lnth int
694 // list of items
695 if list, ok := j.jsonContent.([]interface{}); ok {
696 lnth = len(list)
697 }
698 // return map len // TODO: need to think about map
699 if m, ok := j.jsonContent.(map[string]interface{}); ok {
700 lnth = len(m)
701 }
702 // group data items
703 if m, ok := j.jsonContent.(map[string][]interface{}); ok {
704 lnth = len(m)
705 }
706
707 return lnth
708 }
709
710 // Out write the queried data to defined custom type
711 func (j *JSONQ) Out(v interface{}) {
712 data, err := json.Marshal(j.Get())
713 if err != nil {
714 j.addError(err)
715 return
716 }
717 if err := json.Unmarshal(data, &v); err != nil {
718 j.addError(err)
719 }
720 }
721
722 // Writer write the queried data to a io.Writer
723 func (j *JSONQ) Writer(w io.Writer) {
724 err := json.NewEncoder(w).Encode(j.Get())
725 if err != nil {
726 j.addError(err)
727 return
728 }
729 }
730
731 // More provides the functionality to query over the resultant data. See https://github.com/thedevsaddam/gojsonq/wiki/Queries#More
732 func (j *JSONQ) More() *JSONQ {
733 j.raw = nil
734 j.rootJSONContent = j.Get()
735 j.node = ""
736 j.queries = make([][]query, 0)
737 j.attributes = make([]string, 0)
738 j.queryIndex = 0
739 j.limitRecords = 0
740 j.distinctProperty = ""
741 return j
742 }
743
744 // getFloatValFromArray returns a list of float64 values from array/map for aggregation
745 func (j *JSONQ) getFloatValFromArray(arr []interface{}, property ...string) []float64 {
746 var ff []float64
747 for _, a := range arr {
748 if av, ok := a.(float64); ok {
749 if len(property) > 0 {
750 j.addError(fmt.Errorf("unnecessary property name for array"))
751 return nil
752 }
753 ff = append(ff, av)
754 }
755 if mv, ok := a.(map[string]interface{}); ok {
756 if len(property) == 0 {
757 j.addError(fmt.Errorf("property name can not be empty for object"))
758 return nil
759 }
760 if fi, ok := mv[property[0]]; ok {
761 if flt, ok := fi.(float64); ok {
762 ff = append(ff, flt)
763 } else {
764 j.addError(fmt.Errorf("property %s's value '%v' is not numeric", property[0], fi))
765 return nil
766 }
767 } else {
768 j.addError(fmt.Errorf("property '%s' does not exist", property[0]))
769 return nil
770 }
771 }
772 }
773
774 return ff
775 }
776
777 // getAggregationValues returns a list of float64 values for aggregation
778 func (j *JSONQ) getAggregationValues(property ...string) []float64 {
779 j.prepare()
780 if j.distinctProperty != "" {
781 j.distinct()
782 }
783 if j.limitRecords != 0 {
784 j.limit()
785 }
786
787 var ff []float64
788 if arr, ok := j.jsonContent.([]interface{}); ok {
789 ff = j.getFloatValFromArray(arr, property...)
790 }
791
792 if mv, ok := j.jsonContent.(map[string]interface{}); ok {
793 if len(property) == 0 {
794 j.addError(fmt.Errorf("property can not be empty for object"))
795 return nil
796 }
797 if fi, ok := mv[property[0]]; ok {
798 if flt, ok := fi.(float64); ok {
799 ff = append(ff, flt)
800 } else {
801 j.addError(fmt.Errorf("property %s's value '%v' is not numeric", property[0], fi))
802 return nil
803 }
804 } else {
805 j.addError(fmt.Errorf("property '%s' does not exist", property[0]))
806 return nil
807 }
808 }
809 return ff
810 }
811
812 // Sum returns sum of values from array or from map using property
813 func (j *JSONQ) Sum(property ...string) float64 {
814 var sum float64
815 for _, flt := range j.getAggregationValues(property...) {
816 sum += flt
817 }
818 return sum
819 }
820
821 // Avg returns average of values from array or from map using property
822 func (j *JSONQ) Avg(property ...string) float64 {
823 var sum float64
824 fl := j.getAggregationValues(property...)
825 for _, flt := range fl {
826 sum += flt
827 }
828 return sum / float64(len(fl))
829 }
830
831 // Min returns minimum value from array or from map using property
832 func (j *JSONQ) Min(property ...string) float64 {
833 var min float64
834 flist := j.getAggregationValues(property...)
835 if len(flist) > 0 {
836 min = flist[0]
837 }
838 for _, flt := range flist {
839 if flt < min {
840 min = flt
841 }
842 }
843 return min
844 }
845
846 // Max returns maximum value from array or from map using property
847 func (j *JSONQ) Max(property ...string) float64 {
848 var max float64
849 flist := j.getAggregationValues(property...)
850 if len(flist) > 0 {
851 max = flist[0]
852 }
853 for _, flt := range flist {
854 if flt > max {
855 max = flt
856 }
857 }
858 return max
859 }