JSONata: Tip of the Day

T.O.T.D. 01 - splitting a string and picking out a part

Background: Let's say you have devices sending data into NR with topics like:

wemos/node41/solar/voltage
wemos/node13/sysinfo/upTime
wemos/node28/battery/voltage

and msg.payload contains a value.

You want to sent the data to an Iinflux DB and you want to send the fourth part of the topic as the ‘measurement’ (along with the value) and add the second and third parta as a tags. So how do you split them out?

By using the magic of JSONata!

In a change node, you can use the JSONata $split() function to split a string into an array of substrings! In this case you would split the string using the slash (/), so using the expression
$split(topic,"/") you would get back an array of

[
    "wemos",
    "node41",
    "bme280",
    "Humidity"
]

But how do you get the second item? Easy just add [1] at the end of the expression
$split(topic,"/")[1]
and it returns the second item in the array which is "node41"

So you can set
msg.node to $split(topic,"/")[1] and it will be node41
msg.device to $split(topic,"/")[2] and it will be solar
msg.measurement to $split(topic,"/")[3] and it will be `voltage'

and your ready to build your database expression.

6 Likes

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.