Jsonata solution capturing a key name in msg.payload?

Hi, I've spent hours looking at the forum, nodered docs, jsonata docs, tinkering etc to find a solution that for some of you will be really simple and already known. Yes, I could use a function node, but am thinking a change node with jsonata should do it.

With a Sonoff 4CHAN R3 which contains 4 independent switches, I am trying to parse the mqtt messages

stat/heating/underfloor/RESULT {"POWER4":"ON"}

The key value changes and is one of POWER1, POWER2, POWER3, POWER4.

For elegance and simplicity I'd prefer one node that takes this JSON object and outputs a new msg.payload based on both the key and the value.

{ "zone" = "POWER4", "power" = "ON" }

What jsonata would work?

JSONata:

{
    "zone": $keys(payload),
    "power": $lookup(payload, $keys(payload))
    
}

Honestly, not worth the effort, easier to use a function node.

1 Like

That worked a treat, thanks!

For anyone else that gets stuck with the same thing, here's my flow for the Sonoff 4Chan switch for retaining on/off events in InfluxDB.

[{"id":"ad7da3bd.5e463","type":"mqtt in","z":"7294ec0e.c3b4a4","name":"","topic":"stat/heating/underfloor/+","qos":"2","datatype":"json","broker":"2a8957f2.2dd3b8","x":130,"y":660,"wires":[["747bc489.e04ecc"]]},{"id":"747bc489.e04ecc","type":"change","z":"7294ec0e.c3b4a4","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"{ \"zone\": $keys(payload), \"power\": $lookup(payload, $keys(payload)) }","tot":"jsonata"},{"t":"change","p":"payload.power","pt":"msg","from":"ON","fromt":"str","to":"1","tot":"num"},{"t":"change","p":"payload.power","pt":"msg","from":"OFF","fromt":"str","to":"-1","tot":"num"}],"action":"","property":"","from":"","to":"","reg":false,"x":360,"y":660,"wires":[["ee5461b4.e4981"]]},{"id":"ee5461b4.e4981","type":"function","z":"7294ec0e.c3b4a4","name":"MQTT to InfluxDB","func":"msg.payload = \"power,zone=\" + msg.payload.zone + \" power=\" + msg.payload.power ;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":570,"y":660,"wires":[["9dac1a3d.735448"]]},{"id":"9dac1a3d.735448","type":"http request","z":"7294ec0e.c3b4a4","name":"","method":"POST","ret":"txt","paytoqs":"ignore","url":"http://localhost:8086/write?db=nodered","tls":"","persist":true,"proxy":"","authType":"basic","x":750,"y":660,"wires":[[]]},{"id":"2a8957f2.2dd3b8","type":"mqtt-broker","name":"ns2","broker":"192.168.1.8","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""}]

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