数据格式化-字符串切割
字符串切割处理
问题背景
对文本中的每一行执行操作。例如,你想在每一行的开头添加行号。
解决方案
消息拆分 节点可用于将消息拆分为每行一条消息。它后面可以跟操作各行文本所需的节点,然后跟 消息合并 节点,将各行文本重新组合成单个文本块。
示例

示例JSON
[{"id":"df6514f0.029748","type":"inject","z":"4dcd5b540cc77711","name":"inject","repeat":"","crontab":"","once":false,"onceDelay":"","topic":"","payload":"","payloadType":"date","x":170,"y":1400,"wires":[["11f53f61.2f7be1"]]},{"id":"11f53f61.2f7be1","type":"template","z":"4dcd5b540cc77711","name":"","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"one\ntwo\nthree\nfour\nfive","x":300,"y":1400,"wires":[["760c1d71.c29744"]]},{"id":"760c1d71.c29744","type":"split","z":"4dcd5b540cc77711","name":"","splt":"\\n","spltType":"str","arraySplt":"1","arraySpltType":"len","stream":false,"addname":"","x":430,"y":1400,"wires":[["3e427aac.9b9596","ddd85371d7f23a44"]]},{"id":"3e427aac.9b9596","type":"change","z":"4dcd5b540cc77711","name":"Prepend line number","rules":[{"t":"set","p":"payload","pt":"msg","to":"(parts.index+1) & \": \" & payload","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":620,"y":1400,"wires":[["d44d4767.945fd8"]]},{"id":"d44d4767.945fd8","type":"join","z":"4dcd5b540cc77711","name":"","mode":"auto","build":"string","property":"payload","propertyType":"msg","key":"topic","joiner":"\\n","timeout":"","count":"","x":790,"y":1400,"wires":[["bfe3e43b.85fa88"]]},{"id":"bfe3e43b.85fa88","type":"debug","z":"4dcd5b540cc77711","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","x":930,"y":1400,"wires":[]},{"id":"ddd85371d7f23a44","type":"debug","z":"4dcd5b540cc77711","logName":"日志输出","active":true,"tosidebar":true,"console":true,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","logLevel":"info","dataType":"field","format":"handlebars","syntax":"mustache","template":"输出日志: payload 值为 {{payload}}","output":"str","x":590,"y":1480,"wires":[]}]
运行结果
在示例中,注入 和 模板 节点用于注入多行文本块。
one
two
three
four
five
当传递一个字符串时,消息拆分 节点的默认行为是将其拆分为每行一条消息。
调整消息属性 节点使用 JSONata 表达式修改每个消息有效负载:(parts.index+1) & ": " &payload - 它使用 msg.parts.index 获取行号并将其添加到现有的 msg.payload 中。
最后,消息合并 节点将消息重新组合成单个文本块:
1: one
2: two
3: three
4: four
5: five
