You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

  1. 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;
}
  1. 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 data field value and assigns it to msg.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.

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 data value (YOeNkAAg1wQAYjm/pg==) is being passed correctly.

内容的提问来源于stack exchange,提问作者Chandrika Rathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:49:42