gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:04:16 32 4
gpt4 key购买 nike

我需要 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"

    最佳答案

    如果有效载荷已经是一个对象,您可以使用 Change 节点在有效载荷中添加或修改属性,如下所示:
    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 节点将有效负载作为对象输出,并另外保留旧有效负载内容作为新有效负载对象的属性,那么您必须首先在将有效负载更改为对象之前,使用规则将原始有效负载存储在临时变量中:
    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"]]}]

    关于node-red - 如何将对象添加到 Node-RED msg.payload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52015228/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com