From 054f85423bf4b83b39deaab7e096b615dffd491f Mon Sep 17 00:00:00 2001 From: ccamel Date: Sat, 24 Jun 2023 18:34:02 +0200 Subject: [PATCH] fix(logic): fix empty array management in json predicate --- x/logic/predicate/atom.go | 9 +++++++++ x/logic/predicate/json.go | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/x/logic/predicate/atom.go b/x/logic/predicate/atom.go index 88048e0e..14e343f0 100644 --- a/x/logic/predicate/atom.go +++ b/x/logic/predicate/atom.go @@ -22,6 +22,9 @@ var AtomTrue = engine.NewAtom("true") // AtomFalse is the term false. var AtomFalse = engine.NewAtom("false") +// AtomEmptyArray is the term []. +var AtomEmptyArray = engine.NewAtom("[]") + // AtomNull is the term null. var AtomNull = engine.NewAtom("null") @@ -39,3 +42,9 @@ func MakeBool(b bool) engine.Term { return AtomAt.Apply(AtomFalse) } + +// MakeEmptyArray returns is the compound term @([]). +// It is used to represent the empty array in json objects. +func MakeEmptyArray() engine.Term { + return AtomAt.Apply(AtomEmptyArray) +} diff --git a/x/logic/predicate/json.go b/x/logic/predicate/json.go index 19e1e94a..de00066c 100644 --- a/x/logic/predicate/json.go +++ b/x/logic/predicate/json.go @@ -126,6 +126,8 @@ func termsToJSON(term engine.Term, env *engine.Env) ([]byte, error) { return json.Marshal(true) case MakeBool(false).Compare(t, env) == 0: return json.Marshal(false) + case MakeEmptyArray().Compare(t, env) == 0: + return json.Marshal([]json.RawMessage{}) case MakeNull().Compare(t, env) == 0: return json.Marshal(nil) } @@ -168,6 +170,10 @@ func jsonToTerms(value any) (engine.Term, error) { return AtomJSON.Apply(engine.List(attributes...)), nil case []any: elements := make([]engine.Term, 0, len(v)) + if len(v) == 0 { + return MakeEmptyArray(), nil + } + for _, element := range v { term, err := jsonToTerms(element) if err != nil {