Could someone help me understand why evaluate() is returning an empty result, while ast() works correctly? Am I missing something in the way JSONata is being processed inside the Function node?
Any insights or suggestions would be greatly appreciated!
ast(..) returns the abstract syntax tree which is the internal representation of the expression passed to the jsonata(...) function the abstract syntax tree is used by the parser to evaluate the expression.
let arr = ["He", "is", "a", "good", "boy"]
let temp = [ ]
temp[0] = jsonata(`$length(${arr[0]})`).ast();
because you're using backticks (`), the code is evaluate to $length(He) which for JSONata makes no sense since "He" isn't a variable name or anything else. If you want the length of a string, then you need to add quotes:
Interestingly, after your reply, I looked into the JSONata documentation to find information on providing arguments inside evaluate().
[Embedding and Extending JSONata · JSONata]
There, they use await in front of the evaluate() expression.
I added await, and it worked. However, using .evaluate(arr) does not make a difference, meaning both of the following produce the same result. But I don't know why?
So, as of know we have two ways of getting our answer.
Method 1 -> Using node-red util method that you mentioned above.
Method 2 -> Using await infront of evaluate expression
$$ - the base context of data supplied e.g. arr
.length($) - map through the base context (which is an array) and apply $length to each index value e.g $ ( the values of the map loop context)
Just clarify the base context is an arr as the supplied data arr is an array. if you supply an object then the base context would be an object, thus a slightly different expression would be required.
But i cannot able in this format { "a": 4, "b": 4, "c": 4, "d": -5 }. Can you give me some kind of hint? Though long method gave us the desired result.
I did tried creating a array of keys and array of values seperately and used zip function, but that will create array of array