Node-RED解析Payload数据遇阻,寻求简易解决方案
Hey there! I see you've got your Node-RED setup talking to multiple PLCs, but ran into a snag parsing that payload. The good news is you don't need splice or split here—those are for working with strings, and your payload is already a JavaScript object (Node-RED automatically parses JSON payloads by default).
Here's the simplest way to extract the d field (or any other field) using a Function node:
Step 1: Basic Extraction (Payload is Already an Object)
Drop a Function node into your flow, and paste this code:
// Extract the "d" value from the payload object const dValue = msg.payload.d; // Replace original payload with just the "d" value for downstream nodes msg.payload = dValue; // OR keep the original payload and add the d value as a separate property: // msg.deviceReading = dValue; return msg;
If you want to pull out multiple fields at once, you can use object destructuring for cleaner code:
// Grab all fields you need in one line const { d, dt, ts, q } = msg.payload; // Example: Build a custom payload with renamed fields msg.payload = { deviceReading: d, deviceType: dt, timestamp: ts, quality: q }; return msg;
Why Your splice/split Approach Didn't Work
split() and splice() are methods for strings and arrays, respectively. Since your payload is already parsed into a JS object, you can directly access its properties using dot notation (msg.payload.d) or bracket notation (msg.payload["d"])—no need to manipulate raw strings here.
Edge Case: If Your Payload is a String (Not Parsed)
If for some reason Node-RED didn't auto-parse the JSON into an object (unlikely, but possible), you can first convert it to an object with JSON.parse():
// Convert string payload to a usable object first const payloadObj = JSON.parse(msg.payload); const dValue = payloadObj.d; msg.payload = dValue; return msg;
That's it—this should get you up and running in no time!
内容的提问来源于stack exchange,提问作者Kevin Williams

