Skip to content

Commit

Permalink
Support simple syntax for accessing json. Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zix99 committed Nov 29, 2019
1 parent db9a6f8 commit 0f5c88f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
4 changes: 3 additions & 1 deletion docs/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,12 @@ Good for tabulate output separation.

## Json

Syntax: `{json field expression}`
Syntax: `{json field expression}` or `{json expression}`

Extract a JSON value based on the expression statement from [gjson](https://github.com/tidwall/gjson)

When only 1 argument is present, it will assume the JSON is in `{0}` (Full match)

See: [json](json.md) for more information.

## Time
Expand Down
21 changes: 14 additions & 7 deletions pkg/expressions/funcsJson.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ import (
)

func kfJson(args []KeyBuilderStage) KeyBuilderStage {
if len(args) != 2 {
return stageError(ErrorArgCount)
if len(args) == 1 {
return KeyBuilderStage(func(context KeyBuilderContext) string {
json := context.GetMatch(0)
expression := args[0](context)
return gjson.Get(json, expression).String()
})
} else if len(args) == 2 {
return KeyBuilderStage(func(context KeyBuilderContext) string {
json := args[0](context)
expression := args[1](context)
return gjson.Get(json, expression).String()
})
} else {
return stageLiteral(ErrorArgCount)
}
return KeyBuilderStage(func(context KeyBuilderContext) string {
json := args[0](context)
expression := args[1](context)
return gjson.Get(json, expression).String()
})
}
8 changes: 8 additions & 0 deletions pkg/expressions/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ func TestJson(t *testing.T) {
testExpression(t, mockContext(`{"abc":123}`), `{json {0} abc}`, "123")
}

func TestJsonSingleArg(t *testing.T) {
testExpression(t, mockContext(`{"abc":456}`), `{json abc}`, "456")
}

func TestJsonManyArgs(t *testing.T) {
testExpression(t, mockContext(`{"abc":456}`), `{json {0} abc woops}`, "<ARGN>")
}

func TestFormat(t *testing.T) {
testExpression(t, mockContext(), `{format "%10s" abc}`, " abc")
}
Expand Down

0 comments on commit 0f5c88f

Please sign in to comment.