请求协助:将MQTT通道sensor/X与sensor/Y数据合并为单个JSON对象
How to Combine
sensor/X and sensor/Y MQTT Values into a Single JSON Object in Node-RED Got it, let's sort this out. The problem with your current flow is that it processes each MQTT message from sensor/X and sensor/Y separately—there's no mechanism to cache both values and merge them into one JSON object once both are available. Here's a step-by-step solution using a Function node:
Step 1: Adjust Your Node-RED Flow
- Remove the existing
jsonnode between yourmqtt inanddebugnodes. - Add a Function node in its place (connect
mqtt in→Function→debug).
Step 2: Paste This JavaScript Code into the Function Node
This code uses Node-RED's context storage to cache values from both topics, then outputs the combined JSON only when both X and Y values are present:
// Retrieve cached sensor values from context (initialize if empty) let sensorCache = context.get('sensorCache') || { X: null, Y: null }; // Parse the incoming MQTT topic to identify if it's X or Y const topicSegments = msg.topic.split('/'); const sensorType = topicSegments[1]; // Will be "X" or "Y" // Update the cache with the current message's payload if (sensorType === 'X') { sensorCache.X = msg.payload; // If your Python code sends JSON instead of raw numbers, use this instead: // sensorCache.X = msg.payload.value; // Adjust based on your actual payload structure } else if (sensorType === 'Y') { sensorCache.Y = msg.payload; // Similarly, use msg.payload.value if sending JSON } // Save the updated cache back to context context.set('sensorCache', sensorCache); // Only output the combined JSON if both values are available if (sensorCache.X !== null && sensorCache.Y !== null) { // Create the final combined payload msg.payload = { X: sensorCache.X, Y: sensorCache.Y }; // Optional: Clear the cache after output (remove if you want to keep updating with new values) // context.set('sensorCache', { X: null, Y: null }); return msg; } else { // Don't output anything if one value is missing return null; }
Step 3: Test the Flow
- Send a value to
sensor/Xfrom your Python code—no output will appear in the debug tab yet (sinceYis missing). - Send a value to
sensor/Y—the debug tab will now show your combined JSON object:{ "X": [your X value], "Y": [your Y value] }.
Key Notes
- Payload Structure: If your Python code sends JSON payloads (e.g.,
{"value": 42}) instead of raw numbers, adjust the code to referencemsg.payload.valueinstead ofmsg.payload. - Persistent Caching: By default, Node-RED uses in-memory context—if you restart Node-RED, the cached values will be lost. For persistent storage, configure context storage to use a file or database.
- Continuous Updates: If you want to output an updated combined object every time either
XorYchanges (instead of only once), remove the optional cache-clearing line. This way, every new value will trigger an output with the latest combined data.
内容的提问来源于stack exchange,提问作者RogerLM
相关产品推荐
相关产品推荐

