Skip to content
Julian Knight edited this page Aug 2, 2017 · 9 revisions

A list of some useful Node-RED flavoured JSONata recipes

General

Global and Flow context variables

( {
  "aGlobalVariable": $globalContext('globalVariableName'),
  "aFlowVariable": $flowContext('flowVariableName')
} )

Extract specific element from a context variable

This shows how to extract an element from a context variable based on the msg.topic and assuming you have a variable that is keyed on topic. An example might be a global variable keyed on sensor ID that contains sensor locations where you want to add the location to the data from the sensor to pass on to MQTT.

{
   "location": $globalContext('locations["' & topic & '"]'),
   "origPayload": payload
}

Accessing msg

Object entities are exposed directly as names, e.g. msg.payload is accessed simply as "payload". If you want to access the whole msg object, you need to use the "$" variable at the top level of your expression. e.g.

$._msgid

would return the unique message id. If you end up using functions or other enclosures, you can use $$ to access the top level object.

Change Node Recipes

Add extra levels to the start of a topic

Use Set against msg.topic and use the following JSONata expression:

"EXTRA/LEVELS/" & topic

Recreate the msg on the msg.payload

Sometimes you might want to move the content of the msg to msg.payload. For example, if you wanted to send the msg as a debug to MQTT. You cannot do this directly (setting msg.payload to $) as the system thinks this is a circular reference and blocks it. So you have to recreate the msg manually. I include a list of the msg's keys so that you can know if you missed anything.

{
  "topic": topic,
  "payload": payload,
  "_msgid": _msgid,
  "msgKeys": $keys($),
}

There are undoubtedly other ways to do this in a more automated way.

Clone this wiki locally