Change node {} syntax

I want to change msg.payload from a single value to a javascript object.

In a function it's one line
msg.payload = { temperature: msg.payload};

In a change node I can do it like this, which is very inelegant

No doubt it can be done with a J: expression - a system so opaque it makes regular expressions seem transparent! :face_with_symbols_over_mouth:
But can it be done with a single Set {} line?

What is the right low-code way to achieve this change?

image

1 Like

Ah. That explains why the Move option exists! :grinning:

But it's not applicable to a more complex situation eg transforming [120, 95] to {temperature: 120, humidity: 95} ?

try this

[{"id":"f1d72adafbd635b7","type":"change","z":"00a35f2f631d08be","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"{\"t\":payload[0], \"h\":payload[1]}","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":460,"y":540,"wires":[["5a8401db3a20ab69"]]}]

you need to expand the names.

Every time I see struggling with such data sources where output is just an array of numbers I just need to ask - can't it be improved.
Because of -
Can you trust the data to :

  • be always an array
  • always having same amount of elements
  • always having elements in same order

If you can, fine. If not - it is seriously source of (mostly hard to find and fix) failures.

3 Likes

Thanks for the J: solution Paul. I recognise J's utility but I can't warm to it...

hotNipi makes a good point that the incoming message shouldn't really be just a value or an array of values.
What I am actually trying to do is construct a mariadb prepared query. My selection criteria come from a dropdown which returns just the value - "January".
I could use a Change node to transform this to an object - {month: "January"} but ... [GOTO Line 1] :upside_down_face:

Edit - OK I can make the dropdown return a string {"month":"January"} and pass it through a Json parser node.

Not quite but it can be done trivially (and a lot more of course) by using JSONata.

Not really for something like this. It really would be as simple as you envisage it.

Nope but jsonata something like:

{"temperature": payload[0], "humidity": payload[1]}

will probably work (didn't actually try it but i think it would work like that).

2 Likes

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