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

"if" operation fails when using single key objects as return values

Open MustardForBreakfast opened this issue 5 years ago • 4 comments

Observed in version 1.2.2

The following behaves as expected:

jsonLogic.apply({
  "if": [
    {"===": [1,1]},
    {
      "key_1": true,
      "key_2": false
    },
    {
      "key_1": false,
      "key_2": false
    },
  ]
})

Result: { key_1: true, key_2: false }

Yet, the following throws an error:

jsonLogic.apply({
  "if": [
    {"===": [1,1]},
    {
      "key_1": true,
    },
    {
      "key_1": false,
    },
  ]
})

Result: Error: Unrecognized operation key_1

MustardForBreakfast avatar Jan 15 '20 22:01 MustardForBreakfast

I think this might be able to be resolved by updating the is_logic function: https://github.com/jwadhams/json-logic-js/blob/a15f528919346f2ec7d82bd4fc91c41481546c01/logic.js#L179-L186

to add an extra condition to verify that the single key is present in the available operators:

  jsonLogic.is_logic = function(logic) {
    return (
      typeof logic === "object" && // An object
      logic !== null && // but not null
      ! Array.isArray(logic) && // and not an array
      Object.keys(logic).length === 1  && // with exactly one key
      Object.keys(logic)[0] in operations  // and the key is an operator
    );
  };

mplanchard avatar Mar 09 '20 22:03 mplanchard

There is a workaround here: https://github.com/jwadhams/json-logic-js/issues/35#issuecomment-411625940

sfeilmeier avatar Apr 23 '20 19:04 sfeilmeier

@mplanchard I don't think the lib is being maintained, is that extra code on a fork or did you sent a PR?

ppazos avatar Jun 26 '20 04:06 ppazos

@ppazos I haven't forked this directly, but we did make a version of it in Rust that is published as a webassembly module. If you're able to load WASM into your environment, you can check that out here: https://github.com/Bestowinc/json-logic-rs

mplanchard avatar Mar 09 '21 02:03 mplanchard