JSONata vs JavaScript

Is there a good reason why the behavior of JSONata $number(value) is different than Javascript Number(value)?

e.g. $number(".5") will fail to cast as a number where as Number(".5") will cast to the numeric value of 0.5 as expected.

I continually find myself using Function nodes (when I don't really want to) because I run into issues like the above when using a Change node and JSONata.

You might need to ask that question on the JSONata site rather than here?

The other question I'd ask is why you prefer JSONata over JavaScript? JS is a lot more efficient in general and really, the only benefit of JSONata is when it can do object reshaping easily for you that would be complex in JavaScript.

It's not that I prefer JSONata over JS... it's just the paradigm of Node-RED being a 'low code' flow based, programming tool I was trying to minimize my usage of the Function node and rely on various functional type nodes (such as the Change node)... but I continually run into situations like this where I need to "sanitize" the incoming data and I end up reverting to Function nodes with bits of JS.

I just thought perhaps I was missing something or didn't understand how to use some of the built-in nodes effectively?

2 Likes

JSONata is pretty strict. TBH ".5" is not something I would enter in any programming language, as it's easy not to see the decimal point when debugging. Just my opinion.

$number("0.5")	

works.

:wink: nope.

I think you will find that most people who know JavaScript but who use Node-RED use function nodes a lot because we can create a small nugget of code that itself does a lot in a few lines. But we use Node-RED because it can do a LOT with no code and it gives us an operating environment that is consistent and robust.

JSONata is designed to work with strict JSON valid types. ".5" is not a valid representation of a number in JSON, so JSONata doesn't handle it.

A case could certainly be made for it to be slightly more relaxed... but that's something to take up with the JSONata project.

Thanks for the explanation Nick.

I don't disagree... but in this case I'm dealing with data being pulled from a database I have no control over. And when you are dealing with multi-purpose text fields, "numbers" can be stored any which way the user inputs them... thus the need to "sanitize" the data as it is pulled in.

2 Likes

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