From fcb472129bbf986f6100ca9662cff1706c93f977 Mon Sep 17 00:00:00 2001 From: Diego Henrique Oliveira Date: Fri, 8 Dec 2023 10:06:48 -0300 Subject: [PATCH] Verify array before try to access any position --- jsonlogic_test.go | 10 ++++++++++ vars.go | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/jsonlogic_test.go b/jsonlogic_test.go index aa9e548..e7516fe 100644 --- a/jsonlogic_test.go +++ b/jsonlogic_test.go @@ -807,6 +807,16 @@ func TestIssue71_example_max(t *testing.T) { assert.JSONEq(t, expected, result.String()) } +func TestIssue74(t *testing.T) { + logic := strings.NewReader(`{"if":[ false, {"var":"values.0.categories"}, "else" ]}`) + data := strings.NewReader(`{ "values": [] }`) + + var result bytes.Buffer + _ = Apply(logic, data, &result) + expected := `"else"` + assert.JSONEq(t, expected, result.String()) +} + func TestJsonLogicWithSolvedVars(t *testing.T) { rule := json.RawMessage(`{ "or":[ diff --git a/vars.go b/vars.go index d619e6e..3558899 100644 --- a/vars.go +++ b/vars.go @@ -91,7 +91,12 @@ func getVar(value, data interface{}) interface{} { } if isSlice(data) { - _value = data.([]interface{})[int(toNumber(part))] + pos := int(toNumber(part)) + container := data.([]interface{}) + if pos >= len(container) { + return _default + } + _value = container[pos] } if _value == nil {