简体   繁体   English

node-red 将 json 字符串解析为 msg.payload

[英]node-red parsing a json string to msg.payload

Noob question菜鸟问题

I am using the snmp function to collect data via oid lists.我正在使用 snmp 函数通过 oid 列表收集数据。 I have extracted the data and used the json function to parse the data into a json string seen below.我提取了数据并使用 json 函数将数据解析为如下所示的 json 字符串。

msg.payload: string[81] "[{"oid":"1.3.6.1.4.1.38783.3.3.1.1.1.0","type":2,"value":53800,"tstr":"Integer"}]" msg.payload: string[81] "[{"oid":"1.3.6.1.4.1.38783.3.3.1.1.1.0","type":2,"value":53800,"tstr":"Integer"}]"

I am trying to write a function to strip out "value":53800 from this string and output it in msg.payload .我正在尝试编写一个函数来从该字符串中删除"value":53800 53800 并将其输出到msg.payload中。

I have tried below but it returns我在下面尝试过但它返回

"TypeError: Cannot assign to read only property '_msgid' of "value":53700,"tstr":"Integer"}]" “TypeError:无法分配给“value”的只读属性'_msgid' "value":53700,"tstr":"Integer"}]"

var msg = msg.payload;
var value = msg.substr(49,62);

return value;

Don't try and split the string up like that, it's too prone to errors if the value lengths ever change.不要尝试像那样拆分字符串,如果值长度发生变化,它很容易出错。

Instead run the message through the JSON node before the function node.而是在函数节点之前通过 JSON 节点运行消息。

在此处输入图像描述

This will parse the string and generate a proper JSON object.这将解析字符串并生成适当的 JSON 对象。

You can then access value field as such:然后,您可以这样访问值字段:

var value = msg.payload[0].value;
msg.payload = value;
return msg;

The Cannot assign to read only property error is because you returned a string from the function. Cannot assign to read only property错误是因为您从函数返回了一个字符串。 You need to return a message JSON object not a string.您需要返回消息 JSON 对象而不是字符串。 My example sets the msg.payload to the required value.我的示例将msg.payload设置为所需的值。

For your JSON the following code will work in the function:对于您的 JSON,以下代码将在函数中起作用:

var value = msg.payload.value;
msg.payload = value;
return msg;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM