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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44945068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:48:00  来源:igfitidea点击:

node-red parsing a json string to msg.payload

javascriptjsonstringsplitnode-red

提问by Michael

Noob question

菜鸟问题

I am using the snmp function to collect data via oid lists. I have extracted the data and used the json function to parse the data into a json string seen below.

我正在使用 snmp 函数通过 oid 列表收集数据。我已经提取了数据并使用 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 : 字符串[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":53800from this string and output it in msg.payload.

我正在尝试编写一个函数来"value":53800从这个字符串中剥离出来并在msg.payload.

I have tried below but it returns

我在下面尝试过,但它返回

"TypeError: Cannot assign to read only property '_msgid'of "value":53700,"tstr":"Integer"}]"

“类型错误:无法分配给只读属性'_msgid'"value":53700,"tstr":"Integer"}]"

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

return value;

回答by hardillb

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 节点运行消息。

enter image description here

在此处输入图片说明

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 propertyerror is because you returned a string from the function. You need to return a message JSON object not a string. My example sets the msg.payloadto the required value.

Cannot assign to read only property错误是因为你返回从函数的字符串。您需要返回消息 JSON 对象而不是字符串。我的示例将 设置msg.payload为所需的值。

回答by spiralbrain

For your JSON the following code will work in the function:

对于您的 JSON,以下代码将在函数中工作:

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