• V
 

JSON 互转

问题

您希望在 JSON 字符串和它所代表的 JavaScript 对象之间转换消息属性。

解决方案

JSON 节点可用于在两种格式之间进行转换。

示例

[{"id":"634256b7.2d6818","type":"inject","z":"64133d39.bb0394","name":"JSON String","topic":"","payload":"{\"a\":1}","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":110,"y":80,"wires":[["a2fe0fc8.095e1"]]},{"id":"a2fe0fc8.095e1","type":"json","z":"64133d39.bb0394","name":"","property":"payload","action":"","pretty":false,"x":270,"y":80,"wires":[["9a4ce2b8.47698"]]},{"id":"9a4ce2b8.47698","type":"debug","z":"64133d39.bb0394","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":430,"y":80,"wires":[]},{"id":"80032e2.7c92cd","type":"inject","z":"64133d39.bb0394","name":"Object","topic":"","payload":"{\"a\":1}","payloadType":"json","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":90,"y":120,"wires":[["cd40a0f4.4f5ac"]]},{"id":"cd40a0f4.4f5ac","type":"json","z":"64133d39.bb0394","name":"","property":"payload","action":"","pretty":false,"x":270,"y":120,"wires":[["478b4106.4fd7c"]]},{"id":"478b4106.4fd7c","type":"debug","z":"64133d39.bb0394","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":430,"y":120,"wires":[]}]

讨论

在此示例中,第一个流程注入 JSON 字符串 '{"a":1}'JSON 节点将其转换为等效的 JavaScript 对象。

第二个流程则执行相反的操作,注入对象 { a: 1 } 并将其转换为 JSON。

JSON 节点默认会检测它接收到的内容进行转换。它也可以配置为确保属性是给定类型。例如,如果您的流程可以接收 JSON 或对象,则可以将 JSON 节点配置为确保属性是对象。