Skip to content

Commit 2fd0cff

Browse files
authored
Merge pull request #65 from sadlil/refactor
Code refactor by keeping version compatibility
2 parents b2d1098 + 0ba7618 commit 2fd0cff

13 files changed

+348
-287
lines changed

Makefile

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Makefile includes some useful commands to build or format incentives
2+
# More commands could be added
3+
4+
# Variables
5+
PROJECT = gojsonq
6+
REPO_ROOT = github.com/thedevsaddam
7+
ROOT = ${REPO_ROOT}/${PROJECT}
8+
9+
fmt:
10+
goimports -w .
11+
gofmt -s -w .
12+
13+
compile: fmt
14+
go install .
15+
16+
check: fmt
17+
golangci-lint run --deadline 10m ./...
18+
staticcheck -checks="all,-S1*" ./...
19+
20+
dep:
21+
go mod download
22+
go mod vendor
23+
go mod tidy
24+
25+
# A user can invoke tests in different ways:
26+
# - make test runs all tests;
27+
# - make test TEST_TIMEOUT=10 runs all tests with a timeout of 10 seconds;
28+
# - make test TEST_PKG=./model/... only runs tests for the model package;
29+
# - make test TEST_ARGS="-v -short" runs tests with the specified arguments;
30+
# - make test-race runs tests with race detector enabled.
31+
TEST_TIMEOUT = 60
32+
TEST_PKGS ?= ./...
33+
TEST_TARGETS := test-short test-verbose test-race test-cover
34+
.PHONY: $(TEST_TARGETS) test
35+
test-short: TEST_ARGS=-short
36+
test-verbose: TEST_ARGS=-v
37+
test-race: TEST_ARGS=-race
38+
test-cover: TEST_ARGS=-cover
39+
$(TEST_TARGETS): test
40+
41+
test: compile
42+
go test -timeout $(TEST_TIMEOUT)s $(TEST_ARGS) $(TEST_PKGS)
43+
44+
clean:
45+
@go clean
46+
47+
.PHONY: help
48+
help:
49+
@$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | \
50+
awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | \
51+
sort | \
52+
egrep -v -e '^[^[:alnum:]]' -e '^$@$$'

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import "github.com/thedevsaddam/gojsonq"
3838

3939
func main() {
4040
const json = `{"name":{"first":"Tom","last":"Hanks"},"age":61}`
41-
name := gojsonq.New().JSONString(json).Find("name.first")
41+
name := gojsonq.New().FromString(json).Find("name.first")
4242
println(name.(string)) // Tom
4343
}
4444
```
@@ -58,7 +58,7 @@ import (
5858

5959
func main() {
6060
const json = `{"city":"dhaka","type":"weekly","temperatures":[30,39.9,35.4,33.5,31.6,33.2,30.7]}`
61-
avg := gojsonq.New().JSONString(json).From("temperatures").Avg()
61+
avg := gojsonq.New().FromString(json).From("temperatures").Avg()
6262
fmt.Printf("Average temperature: %.2f", avg) // 33.471428571428575
6363
}
6464
```

doc.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
// const json = `{"name":{"first":"Tom","last":"Hanks"},"age":61}`
1111
//
1212
// func main() {
13-
// name := gojsonq.New().JSONString(json).Find("name.first")
13+
// name := gojsonq.New().FromString(json).Find("name.first")
1414
// println(name.(string)) // Tom
1515
// }
1616
//

helper.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ func toFloat64(v interface{}) (float64, bool) {
6565

6666
// sortList sorts a list of interfaces
6767
func sortList(list []interface{}, asc bool) []interface{} {
68-
ss := []string{}
69-
ff := []float64{}
70-
result := []interface{}{}
68+
var ss []string
69+
var ff []float64
70+
var result []interface{}
7171
for _, v := range list {
7272
// sort elements for string
7373
if sv, ok := v.(string); ok {
@@ -231,7 +231,8 @@ func getNestedValue(input interface{}, node, separator string) (interface{}, err
231231
}
232232

233233
// makeAlias provide syntactic suger. when provide Property name as "user.name as userName"
234-
// it return userName as output and pure node name like: "user.name". If "user.name" does not use "as" clause then it'll return "user.name", "user.name"
234+
// it return userName as output and pure node name like: "user.name".
235+
// If "user.name" does not use "as" clause then it'll return "user.name", "user.name"
235236
func makeAlias(in, separator string) (string, string) {
236237
const alias = " as "
237238
in = strings.Replace(in, " As ", alias, -1)

helper_test.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,16 +153,18 @@ func Test_toFloat64(t *testing.T) {
153153
expected: 898,
154154
},
155155
{
156-
val: float32(99.01),
157-
expected: 99.01000213623047, // The nearest IEEE754 float32 value of 99.01 is 99.01000213623047; which are not equal (while using ==). Need suggestions for precision float value.
156+
val: float32(99.01),
157+
// The nearest IEEE754 float32 value of 99.01 is 99.01000213623047; which are not equal (while using ==).
158+
// Need suggestions for precision float value.
158159
// one way to solve the comparison using convertFloat(string with float precision)==float64
160+
expected: 99.01000213623047,
159161
},
160162
{
161163
val: float32(-99),
162164
expected: -99,
163165
},
164166
{
165-
val: float64(-99.91),
167+
val: -99.91,
166168
expected: -99.91,
167169
},
168170
{
@@ -375,7 +377,7 @@ func Test_getNestedValue(t *testing.T) {
375377
}
376378

377379
for _, tc := range testCases {
378-
out, err := getNestedValue(content, tc.query, defaultSeperator)
380+
out, err := getNestedValue(content, tc.query, defaultSeparator)
379381
if tc.expectError && err == nil {
380382
t.Error("failed to catch error")
381383
}

jsonq.go

Lines changed: 31 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ import (
1111
// New returns a new instance of JSONQ
1212
func New(options ...OptionFunc) *JSONQ {
1313
jq := &JSONQ{
14-
queryMap: loadDefaultQueryMap(),
14+
queryMap: defaultQueries(),
1515
option: option{
1616
decoder: &DefaultDecoder{},
17-
separator: defaultSeperator,
17+
separator: defaultSeparator,
1818
},
1919
}
2020
for _, option := range options {
@@ -28,7 +28,7 @@ func New(options ...OptionFunc) *JSONQ {
2828
// empty represents an empty result
2929
var empty interface{}
3030

31-
const defaultSeperator = "."
31+
const defaultSeparator = "."
3232

3333
// query describes a query
3434
type query struct {
@@ -60,8 +60,8 @@ func (j *JSONQ) String() string {
6060

6161
// decode decodes the raw message to Go data structure
6262
func (j *JSONQ) decode() *JSONQ {
63-
if err := j.option.decoder.
64-
Decode(j.raw, &j.rootJSONContent); err != nil {
63+
err := j.option.decoder.Decode(j.raw, &j.rootJSONContent)
64+
if err != nil {
6565
return j.addError(err)
6666
}
6767
j.jsonContent = j.rootJSONContent
@@ -85,10 +85,10 @@ func (j *JSONQ) File(filename string) *JSONQ {
8585
return j.decode() // handle error
8686
}
8787

88-
// JSONString reads the json content from valid json string // Deprecated: this method will remove in next major release
88+
// JSONString reads the json content from valid json string
89+
// Deprecated: this method will remove in next major release
8990
func (j *JSONQ) JSONString(json string) *JSONQ {
90-
j.raw = []byte(json)
91-
return j.decode() // handle error
91+
return j.FromString(json)
9292
}
9393

9494
// FromString reads the content from valid json/xml/csv/yml string
@@ -206,7 +206,7 @@ func (j *JSONQ) Where(key, cond string, val interface{}) *JSONQ {
206206
value: val,
207207
}
208208
if j.queryIndex == 0 && len(j.queries) == 0 {
209-
qq := []query{}
209+
var qq []query
210210
qq = append(qq, q)
211211
j.queries = append(j.queries, qq)
212212
} else {
@@ -218,40 +218,40 @@ func (j *JSONQ) Where(key, cond string, val interface{}) *JSONQ {
218218

219219
// WhereEqual is an alias of Where("key", "=", val)
220220
func (j *JSONQ) WhereEqual(key string, val interface{}) *JSONQ {
221-
return j.Where(key, signEq, val)
221+
return j.Where(key, operatorEq, val)
222222
}
223223

224224
// WhereNotEqual is an alias of Where("key", "!=", val)
225225
func (j *JSONQ) WhereNotEqual(key string, val interface{}) *JSONQ {
226-
return j.Where(key, signNotEq, val)
226+
return j.Where(key, operatorNotEq, val)
227227
}
228228

229229
// WhereNil is an alias of Where("key", "=", nil)
230230
func (j *JSONQ) WhereNil(key string) *JSONQ {
231-
return j.Where(key, signEq, nil)
231+
return j.Where(key, operatorEq, nil)
232232
}
233233

234234
// WhereNotNil is an alias of Where("key", "!=", nil)
235235
func (j *JSONQ) WhereNotNil(key string) *JSONQ {
236-
return j.Where(key, signNotEq, nil)
236+
return j.Where(key, operatorNotEq, nil)
237237
}
238238

239239
// WhereIn is an alias for where("key", "in", []string{"a", "b"})
240240
func (j *JSONQ) WhereIn(key string, val interface{}) *JSONQ {
241-
j.Where(key, signIn, val)
241+
j.Where(key, operatorIn, val)
242242
return j
243243
}
244244

245245
// WhereNotIn is an alias for where("key", "notIn", []string{"a", "b"})
246246
func (j *JSONQ) WhereNotIn(key string, val interface{}) *JSONQ {
247-
j.Where(key, signNotIn, val)
247+
j.Where(key, operatorNotIn, val)
248248
return j
249249
}
250250

251251
// OrWhere builds an OrWhere clause, basically it's a group of AND clauses
252252
func (j *JSONQ) OrWhere(key, cond string, val interface{}) *JSONQ {
253253
j.queryIndex++
254-
qq := []query{}
254+
var qq []query
255255
qq = append(qq, query{
256256
key: key,
257257
operator: cond,
@@ -263,33 +263,33 @@ func (j *JSONQ) OrWhere(key, cond string, val interface{}) *JSONQ {
263263

264264
// WhereStartsWith satisfies Where clause which starts with provided value(string)
265265
func (j *JSONQ) WhereStartsWith(key string, val interface{}) *JSONQ {
266-
return j.Where(key, signStartsWith, val)
266+
return j.Where(key, operatorStartsWith, val)
267267
}
268268

269269
// WhereEndsWith satisfies Where clause which ends with provided value(string)
270270
func (j *JSONQ) WhereEndsWith(key string, val interface{}) *JSONQ {
271-
return j.Where(key, signEndsWith, val)
271+
return j.Where(key, operatorEndsWith, val)
272272
}
273273

274274
// WhereContains satisfies Where clause which contains provided value(string)
275275
func (j *JSONQ) WhereContains(key string, val interface{}) *JSONQ {
276-
return j.Where(key, signContains, val)
276+
return j.Where(key, operatorContains, val)
277277
}
278278

279279
// WhereStrictContains satisfies Where clause which contains provided value(string).
280280
// This is case sensitive
281281
func (j *JSONQ) WhereStrictContains(key string, val interface{}) *JSONQ {
282-
return j.Where(key, signStrictContains, val)
282+
return j.Where(key, operatorStrictContains, val)
283283
}
284284

285285
// WhereLenEqual is an alias of Where("key", "leneq", val)
286286
func (j *JSONQ) WhereLenEqual(key string, val interface{}) *JSONQ {
287-
return j.Where(key, signLenEq, val)
287+
return j.Where(key, operatorLenEq, val)
288288
}
289289

290290
// WhereLenNotEqual is an alias of Where("key", "lenneq", val)
291291
func (j *JSONQ) WhereLenNotEqual(key string, val interface{}) *JSONQ {
292-
return j.Where(key, signLenNotEq, val)
292+
return j.Where(key, operatorLenNotEq, val)
293293
}
294294

295295
// findInArray traverses through a list and returns the value list.
@@ -428,7 +428,7 @@ func (j *JSONQ) Distinct(property string) *JSONQ {
428428
// distinct builds distinct value using provided attribute/column/property
429429
func (j *JSONQ) distinct() *JSONQ {
430430
m := map[string]bool{}
431-
dt := []interface{}{}
431+
var dt = make([]interface{}, 0)
432432
if aa, ok := j.jsonContent.([]interface{}); ok {
433433
for _, a := range aa {
434434
if vm, ok := a.(map[string]interface{}); ok {
@@ -478,8 +478,7 @@ func (j *JSONQ) sortBy(property string, asc bool) *JSONQ {
478478

479479
// only return selected properties in result
480480
func (j *JSONQ) only(properties ...string) interface{} {
481-
result := []interface{}{}
482-
481+
var result = make([]interface{}, 0)
483482
if aa, ok := j.jsonContent.([]interface{}); ok {
484483
for _, am := range aa {
485484
tmap := map[string]interface{}{}
@@ -514,7 +513,7 @@ func (j *JSONQ) OnlyR(properties ...string) (*Result, error) {
514513
return NewResult(v), nil
515514
}
516515

517-
// Pluck build an array of vlaues form a property of a list of objects
516+
// Pluck build an array of values form a property of a list of objects
518517
func (j *JSONQ) Pluck(property string) interface{} {
519518
j.prepare()
520519
if j.distinctProperty != "" {
@@ -523,7 +522,7 @@ func (j *JSONQ) Pluck(property string) interface{} {
523522
if j.limitRecords != 0 {
524523
j.limit()
525524
}
526-
result := []interface{}{}
525+
var result = make([]interface{}, 0)
527526
if aa, ok := j.jsonContent.([]interface{}); ok {
528527
for _, am := range aa {
529528
if mv, ok := am.(map[string]interface{}); ok {
@@ -536,7 +535,7 @@ func (j *JSONQ) Pluck(property string) interface{} {
536535
return result
537536
}
538537

539-
// PluckR build an array of vlaues form a property of a list of objects and return as Result instance
538+
// PluckR build an array of values form a property of a list of objects and return as Result instance
540539
func (j *JSONQ) PluckR(property string) (*Result, error) {
541540
v := j.Pluck(property)
542541
if err := j.Error(); err != nil {
@@ -678,7 +677,7 @@ func (j *JSONQ) FindR(path string) (*Result, error) {
678677
// This could be a length of list/array/map
679678
func (j *JSONQ) Count() int {
680679
j.prepare()
681-
lnth := 0
680+
var lnth int
682681
// list of items
683682
if list, ok := j.jsonContent.([]interface{}); ok {
684683
lnth = len(list)
@@ -716,7 +715,7 @@ func (j *JSONQ) Writer(w io.Writer) {
716715
}
717716
}
718717

719-
// More provides the functionalities to query over the resultant data. See https://github.com/thedevsaddam/gojsonq/wiki/Queries#More
718+
// More provides the functionality to query over the resultant data. See https://github.com/thedevsaddam/gojsonq/wiki/Queries#More
720719
func (j *JSONQ) More() *JSONQ {
721720
j.raw = nil
722721
j.rootJSONContent = j.Get()
@@ -731,7 +730,7 @@ func (j *JSONQ) More() *JSONQ {
731730

732731
// getFloatValFromArray returns a list of float64 values from array/map for aggregation
733732
func (j *JSONQ) getFloatValFromArray(arr []interface{}, property ...string) []float64 {
734-
ff := []float64{}
733+
var ff []float64
735734
for _, a := range arr {
736735
if av, ok := a.(float64); ok {
737736
if len(property) > 0 {
@@ -772,7 +771,7 @@ func (j *JSONQ) getAggregationValues(property ...string) []float64 {
772771
j.limit()
773772
}
774773

775-
ff := []float64{}
774+
var ff []float64
776775
if arr, ok := j.jsonContent.([]interface{}); ok {
777776
ff = j.getFloatValFromArray(arr, property...)
778777
}

0 commit comments

Comments
 (0)