Search code examples
node-red

How to add an object to the Node-RED msg.payload


I need the Accel object as part of the payload object:

  • msg.payload.Accel.x : 1
  • msg.payload.Accel.y : 2
  • msg.payload.Accel.z : 3

How can I add Accel and x,z,y to payload, ideally using the change node?

I tried this already:

msg.payload.Accel['x'] = 1;
return msg;

and got an error:

"TypeError: Cannot set property 'x' of undefined"

Solution

  • If payload is already an object, you can use a Change node to add or modify properties in payload like this:

    enter image description here

    [{"id":"a5a26aa9.8e0c48","type":"change","z":"b46a495a.46a938","name":"","rules":[{"t":"set","p":"payload.Accel.x","pt":"msg","to":"1","tot":"num"},{"t":"set","p":"payload.Accel.y","pt":"msg","to":"2","tot":"num"},{"t":"set","p":"payload.Accel.z","pt":"msg","to":"3","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":270,"y":260,"wires":[["85a0573d.ed8788","e0cc9521.5adb38"]]}]
    

    If payload comes in as a string (or another non-object) and you want to use a Change node to output payload as an object, you first have to use a rule to set msg.payload to an empty JSON object, then further rules to set msg.payload.Accel.x to 1, etc.:

    enter image description here

    [{"id":"a5a26aa9.8e0c48","type":"change","z":"b46a495a.46a938","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"{}","tot":"json"},{"t":"set","p":"payload.Accel.x","pt":"msg","to":"1","tot":"num"},{"t":"set","p":"payload.Accel.y","pt":"msg","to":"2","tot":"num"},{"t":"set","p":"payload.Accel.z","pt":"msg","to":"3","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":270,"y":260,"wires":[["85a0573d.ed8788","e0cc9521.5adb38"]]}]
    

    If payload comes in as a string (or another non-object) and you want to use a Change node to output payload as an object, and additionally preserve the old payload content as a property of the new payload object, then you have to first use a rule to store the original payload in a temp variable before you change payload to an object:

    enter image description here

    [{"id":"a5a26aa9.8e0c48","type":"change","z":"b46a495a.46a938","name":"","rules":[{"t":"set","p":"temp","pt":"msg","to":"payload","tot":"msg"},{"t":"set","p":"payload","pt":"msg","to":"{}","tot":"json"},{"t":"set","p":"payload.Accel.x","pt":"msg","to":"1","tot":"num"},{"t":"set","p":"payload.Accel.y","pt":"msg","to":"2","tot":"num"},{"t":"set","p":"payload.Accel.z","pt":"msg","to":"temp","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":270,"y":260,"wires":[["85a0573d.ed8788","e0cc9521.5adb38"]]}]