json-logic-js
json-logic-js copied to clipboard
Is it possible to return "Undefined"?
{
"==": [
{
"==": [
{
"var": "parameter1"
},
"Y2022"
]
},
"Undefined"
]
}
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