node-red parsing a json string to msg.payload

Michael picture Michael · Jul 6, 2017 · Viewed 27k times · Source

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.

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.

I have tried below but it returns

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

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

return value;

Answer

hardillb picture hardillb · Jul 6, 2017

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.

enter image description here

This will parse the string and generate a proper JSON object.

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. You need to return a message JSON object not a string. My example sets the msg.payload to the required value.