Skip to content

Commit

Permalink
feat: support JSON strings in JQ
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe authored and moshloop committed Sep 25, 2024
1 parent 7a6ee6f commit 133502c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
8 changes: 8 additions & 0 deletions coll/jq.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ func JQ(ctx context.Context, jqExpr string, in interface{}) (interface{}, error)
return nil, fmt.Errorf("jq type conversion: %w", err)
}

if inString, ok := in.(string); ok {
var v map[string]any
if err := json.Unmarshal([]byte(inString), &v); err == nil {
in = v
}

}

iter := query.RunWithContext(ctx, in)
var out interface{}
a := []interface{}{}
Expand Down
7 changes: 6 additions & 1 deletion tests/cel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ func TestCelJSON(t *testing.T) {
Address: &Address{City: "Kathmandu"},
}

personJSONString, _ := json.Marshal(person)

runTests(t, []Test{
{nil, `dyn([{'name': 'John', 'age': 30}]).toJSON()`, `[{"age":30,"name":"John"}]`},
{nil, `[{'name': 'John'}].toJSON()`, `[{"name":"John"}]`},
Expand All @@ -188,10 +190,13 @@ func TestCelJSON(t *testing.T) {
{nil, `'{"name": "John"}'.JSON().name`, `John`},
{nil, `'{"name": "Alice", "age": 30}'.JSON().name`, `Alice`},
{nil, `'[1, 2, 3, 4, 5]'.JSONArray()[0]`, `1`},
{map[string]interface{}{"i": person}, "jq('.Address.city_name', i)", "Kathmandu"},
{map[string]interface{}{"i": person}, "i.toJSONPretty('\t')", "{\n\t\"Address\": {\n\t\t\"city_name\": \"Kathmandu\"\n\t},\n\t\"name\": \"Aditya\"\n}"},
{nil, "[\"Alice\", 30].toJSONPretty('\t')", "[\n\t\"Alice\",\n\t30\n]"},
{nil, "{'name': 'aditya'}.toJSONPretty('\t')", "{\n\t\"name\": \"aditya\"\n}"},

// JQ
{map[string]interface{}{"i": person}, "jq('.Address.city_name', i)", "Kathmandu"},
{map[string]interface{}{"i": personJSONString}, "jq('.Address.city_name', i)", "Kathmandu"},
})
}

Expand Down

0 comments on commit 133502c

Please sign in to comment.