如何将对象添加到Node-RED msg.payload

时间:2018-08-25 08:00:42

标签: node-red

我需要Accel对象作为有效负载对象的一部分:

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

如何理想地使用更改节点将Accel和x,z,y添加到有效载荷中?

我已经尝试过了:

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

并出现错误:

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

2 个答案:

答案 0 :(得分:3)

这完全取决于msg.payload的开头。如果功能节点的输入是字符串,那么msg.payload将是一个字符串,您不能只向其中添加任意属性。

如果输入已经是一个对象,则可以对其进行扩展,但是您需要在该对象中创建中间层,然后才能添加该值。例如假设以下输入msg.payload

{
  foo: 25,
  bar: 'testing'
}

要添加Accel.x,您首先需要添加一个Accel键,然后才能尝试向Accel.x添加一个值。使用功能节点,您可以这样做:

msg.payload.Accel = {};
msg.payload.Accel.x = 1;
msg.payload.Accel['y'] = 2;
return msg;

对于更改节点,它看起来像这样,因为更改节点将为您添加空层:

Change Node Settings

答案 1 :(得分:2)

如果有效载荷已经是一个对象,则可以使用“更改”节点来添加或修改有效载荷中的属性,如下所示:

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"]]}]

如果有效载荷以字符串(或另一个非对象)的形式出现,并且您想使用Change节点将有效载荷作为对象输出,则首先必须使用一条规则将msg.payload设置为空的JSON对象,然后进一步设置规则,将msg.payload.Accel.x设置为1,依此类推:

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"]]}]

如果有效载荷以字符串(或另一个非对象)的形式出现,并且您想使用Change节点将有效载荷作为对象输出,并另外将旧的有效载荷内容保留为新的有效载荷对象的属性,那么您在将有效负载更改为对象之前,必须首先使用规则将原始有效负载存储在temp变量中:

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"]]}]