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.
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:
and for rounding is:
The round function is one of the numeric functions and is described here.
Now image we have a Unix time stamp and we need to convert it into a more readable form for display.
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
JSONata is a very powerful query language for JSON data and is available in the node-red change and switch nodes.
Related tutorials and resources
- JSONata docs
- Transforming data in JSONata
- Try JSONata
- More good examples on transforming msg data