Skip to content

Addition of list mapping #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions gojq.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ func NewQuery(jsonObject interface{}) *JQ {
return &JQ{Data: jsonObject}
}

func (jq *JQ) getKey(context interface{}, path string) (interface{}, error) {
// map
if v, ok := context.(map[string]interface{}); ok {
if val, ok := v[path]; ok {
context = val
} else {
return context, errors.New(fmt.Sprint(path, " does not exist."))
}
} else {
return context, errors.New(fmt.Sprint(path, " is not an object. ", v))
}

return context, nil
}

// Query queries against the JSON with the expression passed in. The exp is separated by dots (".")
func (jq *JQ) Query(exp string) (interface{}, error) {
if exp == "." {
Expand All @@ -71,6 +86,20 @@ func (jq *JQ) Query(exp string) (interface{}, error) {
return nil, errors.New(fmt.Sprint(path, " is not an array. ", v))
}
} else {
// array of maps
if v, ok := context.([]interface{}); ok {
newContext := []interface{}{}
for _, item := range v {
subItem, err := jq.getKey(item, path)
if err != nil {
return nil, err
}
newContext = append(newContext, subItem)
}
context = newContext
return context, nil
}

// map
if v, ok := context.(map[string]interface{}); ok {
if val, ok := v[path]; ok {
Expand Down
34 changes: 34 additions & 0 deletions gojq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,40 @@ func TestParseJsonArray(t *testing.T) {
}
}

func TestMapJsonArray(t *testing.T) {
parserArray, err := NewStringQuery(jsonArray)
if err != nil {
t.Error(err)
}

var pass = []struct {
in string
ex []interface{}
}{
{"name", []interface{}{"elgs", "enny", "sam"}},
}

for _, v := range pass {
result, err := parserArray.Query(v.in)
if err != nil {
t.Error(err)
}
if list, ok := result.([]interface{}); ok {
if len(list) != len(v.ex) {
t.Error("Expected:", v.ex, "actual:", result)
}
for i, expected := range v.ex {
output := list[i]
if expected != output {
t.Error("Expected:", v.ex, "actual:", result)
}
}
} else {
t.Error("Expected:", v.ex, "actual:", result)
}
}
}

var jsonObj = `
{
"name": "sam",
Expand Down