diff --git a/core/condition_test.go b/core/condition_test.go index e43697d9..bbc23d22 100644 --- a/core/condition_test.go +++ b/core/condition_test.go @@ -234,6 +234,13 @@ func TestCondition_evaluate(t *testing.T) { }, { Name: "body-len-array", + Condition: Condition("len([BODY]) == 3"), + Result: &Result{body: []byte("[{\"id\": 1}, {\"id\": 2}, {\"id\": 3}]")}, + ExpectedSuccess: true, + ExpectedOutput: "len([BODY]) == 3", + }, + { + Name: "body-len-keyed-array", Condition: Condition("len([BODY].data) == 3"), Result: &Result{body: []byte("{\"data\": [{\"id\": 1}, {\"id\": 2}, {\"id\": 3}]}")}, ExpectedSuccess: true, @@ -248,6 +255,13 @@ func TestCondition_evaluate(t *testing.T) { }, { Name: "body-len-string", + Condition: Condition("len([BODY]) == 8"), + Result: &Result{body: []byte("john.doe")}, + ExpectedSuccess: true, + ExpectedOutput: "len([BODY]) == 8", + }, + { + Name: "body-len-keyed-string", Condition: Condition("len([BODY].name) == 8"), Result: &Result{body: []byte("{\"name\": \"john.doe\"}")}, ExpectedSuccess: true, diff --git a/jsonpath/jsonpath.go b/jsonpath/jsonpath.go index 1ba82c87..58b7f4c2 100644 --- a/jsonpath/jsonpath.go +++ b/jsonpath/jsonpath.go @@ -9,10 +9,12 @@ import ( // Eval is a half-baked json path implementation that needs some love func Eval(path string, b []byte) (string, int, error) { + if len(path) == 0 && !(len(b) != 0 && b[0] == '[' && b[len(b)-1] == ']') { + // if there's no path AND the value is not a JSON array, then there's nothing to walk + return string(b), len(b), nil + } var object interface{} - err := json.Unmarshal(b, &object) - if err != nil { - // Try to unmarshal it into an array instead + if err := json.Unmarshal(b, &object); err != nil { return "", 0, err } return walk(path, object) @@ -103,5 +105,10 @@ func extractValue(currentKey string, value interface{}) interface{} { } return nil } + if valueAsSlice, ok := value.([]interface{}); ok { + // If the type is a slice, return it + return valueAsSlice + } + // otherwise, it's a map return value.(map[string]interface{})[currentKey] } diff --git a/jsonpath/jsonpath_test.go b/jsonpath/jsonpath_test.go index 3ceba124..c65aaf88 100644 --- a/jsonpath/jsonpath_test.go +++ b/jsonpath/jsonpath_test.go @@ -62,6 +62,14 @@ func TestEval(t *testing.T) { ExpectedOutputLength: 1, ExpectedError: false, }, + { + Name: "array-of-values-with-no-path", + Path: "", + Data: `[1, 2]`, + ExpectedOutput: "[1 2]", // the output is an array + ExpectedOutputLength: 2, + ExpectedError: false, + }, { Name: "array-of-values-and-invalid-index", Path: "ids[wat]",