JSONata function tutorial WIP

In the process of leaning JSONata, I've been creating a tutorial of their Function Library seen in the sidebar here: JSONata Documentation · JSONata using the npm module jsonata - npm

However, I seem to be having a bit of difficulty with two functions in particular. $error and $assert

In the first function node I have:

// $error(message)

// THIS IS A HACKY WORKAROUND
node.error(jsonata("$error('Error 12345')").ast().arguments[0].value);

// msg.payload = jsonata("$error('Error 12345')").evaluate();

// return msg;

The workaround technically works, but seems like a bad way to go about it. The lower method only produces error "[object Object]", is there a way to use the message property in Node-RED as seen in the JSONata documentation?

In the second function I have :

// $assert(condition, message)

// If condition is true, the function returns undefined.
// If condition is false, an exception is thrown with the message as the message of the exception.
const expression = jsonata(`$assert(${msg.payload} % 2 = 0)`);

//const expression = jsonata("$assert($a % 2 = 0, 'The number must be even')");
//expression.assign("a", msg.payload);

msg.payload = expression.evaluate();

return msg;

Both methods only produces error "[object Object]" when false rather than the error message (if exists), any ideas?

You are getting a object you just need to find the property names returned, Use Object.entries() to see exactly what the object is, or or .ast().arguments[0].name to see the values property name. I suspect that the object property you want is .message
I am liitle confused as to where the error "[object Object]" is being displayed/returned.

So it appears that the values property name is undefined, and .message does not exist.

Maybe my 'HACKY WORKAROUND' isn't so bad after all.

I appreciate your assistance. It lead me to this for $assert:

// $assert(condition, message)

// If condition is true, the function returns { "payload": "assertation is true" }.
// If condition is false, an error is thrown, with the message as the message of the error.
msg.payload = jsonata(`$assert(${msg.payload} % 2 = 0, "Number must be even")`);

// HACKY WORKAROUND for message parameter to be usable
// 'if condition' must be relevant to 'assert condition'
if (msg.payload.ast().arguments[0].lhs.lhs.value % 2 == 0) return { "payload": "assertation is true" };
else node.error(`${msg.payload.ast().arguments[1].value}`);

Which is probably as good as it's going to get. Thanks again.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.