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

Is it possible to return "Undefined"?

Open karthik099 opened this issue 1 year ago • 1 comments

{
    "==": [
      {
        "==": [
          {
            "var": "parameter1"
          },
          "Y2022"
        ]
      },
      "Undefined"
    ]
  }

karthik099 avatar Jul 19 '22 06:07 karthik099

The central problem is that undefined is a valid internal JavaScript concept, but it has no parallel in JSON. That's why the standard functionality of var is to return null when var fails a lookup, it works better with other JsonLogic rules and implementations (e.g., undefined is not really a first class concept in PHP, but null is)

You could replace the stock var operator with one that returns undefined when a variable is not found, if that suits the way you use the library?

const jsonLogic = require('./logic.js');

jsonLogic.apply({"var":"nope"}, {}); // returns null, default behavior

const undefinedVar = function(a, not_found) {
  var data = this;
  if (typeof a === "undefined" || a==="" || a===null) {
    return data;
  }
  var sub_props = String(a).split(".");
  for (var i = 0; i < sub_props.length; i++) {
    if (data === null || data === undefined) {
      return not_found;
    }
    // Descending into data
    data = data[sub_props[i]];
    if (data === undefined) {
      return not_found;
    }
  }
  return data;
};

jsonLogic.add_operation('var', undefinedVar);

jsonLogic.apply({"var":"nope"}, {}); // returns undefined

jwadhams avatar Jul 19 '22 15:07 jwadhams