Node-Red Flow Samples/Sharing

Stupid JSONATA Tricks...

In JSONATA you can grab the value of a property of the message object by doing something like this:

$lookup('payload');

If you try and go "deeper" this does not work:

$lookup('payload.value');

As far as I can tell there is no simple command to do this in JSONATA directly.. but with some functional/recursion trickery you can:

(
  $getkey := function($x,$keyVal){
	$count($split($keyVal,'.')) > 1 
	? $x ~> $lookup($split($keyVal,'.')[0]) ~> $getkey($substringAfter($keyVal, $split($keyVal,'.')[0] & '.'))
	: $lookup($x,$keyVal)
  };
  $getkey(msg,'payload.s1.s2.s3.s4');
)
	
Stupid JSONATA tricks example

[{"id":"9fb34974.d1ccd8","type":"debug","z":"af91369d.586338","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"(   $getkey := function($x,$keyVal){ \t$count($split($keyVal,'.')) > 1  \t? $x ~> $lookup($split($keyVal,'.')[0]) ~> $getkey($substringAfter($keyVal, $split($keyVal,'.')[0] & '.')) \t: $lookup($x,$keyVal)   };   $getkey(msg,'payload.s1.s2.s3.s4'); )","targetType":"jsonata","statusVal":"","statusType":"auto","x":580,"y":780,"wires":[]},{"id":"71eadc98.ee5464","type":"inject","z":"af91369d.586338","name":"","props":[{"p":"payload.s1.s2.s3.s4","v":"true","vt":"bool"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":390,"y":780,"wires":[["9fb34974.d1ccd8"]]}]

The above entry creates a function called "$getkey" that calls itself until the entire $keyVal string runs out of "."'s at which point it returns the $lookup() of the final object and $keyVal and unwinds.

Why do this? Well you might store a certain property name in a global or in the case of subflows have a property/env variable that contains the property name you want to use. Of course you could also use a function node but where is the fun in that? :wink:

edit: wanted to be clear that the $getkey parameter used i.e. "payload.s1.s2...." is arbitrary. Likely you would replace it with $env('SOME_VAR'), $globalContext('someVAR') or msg.someProperty etc.

1 Like