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:
We 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
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
- JSONata docs
- Transforming data in JSONata
- Try JSONata
- More good examples on transforming msg data
- Working with JSON Data And JavaScript Objects in Node-Red