如何在Node-RED中用JavaScript提取嵌套JSON里的指定data字段?
Extract "data" Field from Node-RED Payload Using JavaScript
First, let's break down your incoming message: the payload property is a string that combines a LoRa topic prefix and a JSON object containing your target data field. Here's a reliable way to extract that field using a Node-RED Function node:
Step-by-Step Implementation
- Add a Function node to your flow and paste this code:
// Locate the start of the JSON object in the payload string const jsonStartIndex = msg.payload.indexOf('{'); // Handle cases where no JSON is found if (jsonStartIndex === -1) { node.error("No JSON content detected in payload", msg); return null; // Stop processing this message } // Extract just the JSON portion of the payload const jsonString = msg.payload.slice(jsonStartIndex); try { // Parse the JSON string into a JavaScript object const parsedData = JSON.parse(jsonString); // Extract the "data" field and update the payload (or use a new property if needed) msg.payload = parsedData.data; // Alternative: msg.extractedData = parsedData.data; to keep original payload intact return msg; // Pass the modified message downstream } catch (error) { // Handle JSON parsing errors gracefully node.error(`Failed to parse JSON: ${error.message}`, msg); return null; }
- What this code does:
- Finds the starting position of the JSON object in the payload string using
indexOf('{'). - Slices the payload to isolate just the JSON content.
- Parses the JSON string into a usable JavaScript object.
- Extracts the
datafield value and assigns it tomsg.payload(you can adjust this to store it in a custom property if you want to preserve the original payload). - Includes error handling to catch missing JSON or invalid formatting, preventing your flow from crashing.
- Finds the starting position of the JSON object in the payload string using
Testing the Flow
- Connect your input source (like an MQTT node receiving the LoRa packet) to this Function node.
- Add a Debug node after the Function node to verify the extracted
datavalue (YOeNkAAg1wQAYjm/pg==) is being passed correctly.
内容的提问来源于stack exchange,提问作者Chandrika Rathi
相关产品推荐
相关产品推荐

