Node-Red and JSONata for Beginners

JSONata is a lightweight query and transformation language for JSON data and allows queries to be carried out directly on JSON data. —ref

The alternative,and the one I most often use is to convert JSON to JavaScipt and then query it using JavasScript functions.



JSONata Examples

Example 1

Imaging we have have data coming from a temperature sensor and we need to convert the measurement from Centigrade to Fahrenheit or vice versa.

To do this normally we would use a node-red function node with the following code:

let payload=msg.payload;
msg.temp_c= (payload*9/5)+32;
msg.temp_f= (payload-32) * 5 / 9 ;
msg.payload=msg.temp_f.toFixed(2);
return msg;

The code will convert the incoming payload to centigrade and Fahrenheit and also will round to two places.

We could however use change nodes with JSONata instead as shown below:

jsonata-example-change-node-1We use the expression property to enter a JSONata commands.

The code for Fahrenheit to Centigrade is:

(payload-32)*5/9

and for rounding is:

$round((payload-32)*5/9,2)

The round function is one of the numeric functions and is described here.

Example 2

Now image we have a Unix time stamp and we need to convert it into a more readable form for display.

Again we could use JavaScript functions as covered in the time conversion tutorial- Working With Time- Node-Red Programming.

JSONata provides some very simple to use commands for changing the format of time data. See here

As an example we will changeĀ  a Unix millisecond time stamp into ISO 8601 format using the fromMillis() function

jsonata-example2-time

The example flow has more examples of formatting ams is included at the end for download.

References and further reading

The following video covers a few more examples and is really worth a look.

This video is from a lecture and contains the example shown in the video above but the first 10 minutes covers the background of jSONata and is very interesting

Summary

JSONata is a very powerful query language for JSON data and is available in the node-red change and switch nodes.

It is a very good way for manipulating incoming data without have to use a function node and JavaScript code.

Demo flow



Related tutorials and resources

 

Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *