Skip to content

Commit ea5c69d

Browse files
authored
Add Distinct method (#27)
Add support for `Distinct` method
1 parent f0c174e commit ea5c69d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

jsonq.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,32 @@ func (j *JSONQ) SortBy(order ...string) *JSONQ {
380380
return j.sortBy(order[0], asc)
381381
}
382382

383+
// Distinct builds distinct value using provided attribute/column/property
384+
func (j *JSONQ) Distinct(property string) *JSONQ {
385+
j.prepare()
386+
387+
m := map[string]bool{}
388+
dt := []interface{}{}
389+
if aa, ok := j.jsonContent.([]interface{}); ok {
390+
for _, a := range aa {
391+
if vm, ok := a.(map[string]interface{}); ok {
392+
v, err := getNestedValue(vm, property)
393+
if err != nil {
394+
j.addError(err)
395+
} else {
396+
if _, exist := m[toString(v)]; !exist {
397+
dt = append(dt, vm)
398+
m[toString(v)] = true
399+
}
400+
}
401+
}
402+
}
403+
}
404+
// replace the new result with the previous result
405+
j.jsonContent = dt
406+
return j
407+
}
408+
383409
// sortBy sorts list of map
384410
func (j *JSONQ) sortBy(property string, asc bool) *JSONQ {
385411
sortResult, ok := j.jsonContent.([]interface{})

jsonq_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,6 +698,27 @@ func TestJSONQ_SortBy_expecting_empty_as_provided_node_is_not_list(t *testing.T)
698698
assertJSON(t, out, expJSON)
699699
}
700700

701+
func TestJSONQ_Distinct(t *testing.T) {
702+
jq := New().JSONString(jsonStr).
703+
From("vendor.items").
704+
Distinct("price")
705+
expected := `[{"id":1,"name":"MacBook Pro 13 inch retina","price":1350},{"id":2,"name":"MacBook Pro 15 inch retina","price":1700},{"id":3,"name":"Sony VAIO","price":1200},{"id":4,"name":"Fujitsu","price":850},{"id":6,"name":"HP core i7","price":950}]`
706+
out := jq.Get()
707+
assertJSON(t, out, expected, "Distinct expecting result")
708+
}
709+
710+
func TestJSONQ_Distinct_expecting_error(t *testing.T) {
711+
jq := New().JSONString(jsonStr).
712+
From("vendor.items").
713+
Distinct("invalid_key")
714+
expected := `[]`
715+
out := jq.Get()
716+
assertJSON(t, out, expected, "Distinct expecting empty result")
717+
if len(jq.Errors()) == 0 {
718+
t.Error("failed to catch Distinct error")
719+
}
720+
}
721+
701722
func TestJSONQ_Only(t *testing.T) {
702723
jq := New().JSONString(jsonStr).
703724
From("vendor.items")

0 commit comments

Comments
 (0)