json-logic-js icon indicating copy to clipboard operation
json-logic-js copied to clipboard

"in" operator errors out if array value data is null or undefined; Should return false

Open manahga opened this issue 6 years ago • 5 comments

Given the following rule:

{ "in": [ "1", { "var": "MyData.Values" } ] }

Using it on the following data will cause an error when, IMO, it should return false;

{
   "MyData": {
      "Values": null
   }
}

Should be easy enough to check for a null/undefined data set before testing the "in" operation and return false if necessary.

This may also be a problem with other supported array operations. Although, I have not tested them to see.

manahga avatar Oct 17 '17 13:10 manahga

Just an update... It looks like the "all" operator has issues with null/undefined as well. That being said, "none" and "some" seem to be fine.

I also tested "map", "reduce", and "filter". They all worked without issue.

manahga avatar Oct 17 '17 14:10 manahga

I can work on this, you're right it's going to make the library more robust.

In the meantime you might be able to make your rules more robust by using an empty array as your default in your var calls, like

{ "in": [ 
  "1", 
  { "var": ["MyData.Values", [] ] } 
] }

jwadhams avatar Oct 18 '17 15:10 jwadhams

Ah...great! Thanks for the tip.

manahga avatar Oct 18 '17 16:10 manahga

Just as an FYI, the tip above seems to work well for undefined values. However, it still errors out for data that is explicitly set to null like my initial example.

For instance, the following will error out:

//rule
{ "in": [ "1", { "var": ["MyData.Values", []] } ] }

//data
{
   "MyData": {
      "Values": null
   }
}

However this will not:

//rule
{ "in": [ "1", { "var": ["MyData.Values", []] } ] }

//data
{
   "MyData": {}
}

manahga avatar Oct 18 '17 16:10 manahga

Came to report this bug. I fixed locally by adding a "safeIn" function

jsonLogic.add_operation('safeIn', (a, b) => { if(!b || typeof b.indexOf === "undefined") return false; return (b.indexOf(a) !== -1); } )

MaxNodland avatar Oct 25 '17 18:10 MaxNodland