Search code examples
node-redkepserverex

Node-Red function : how to get a specific value out of object as Msg.Payload after inject?


I'm trying to create a Node Red flow and output a graph out of the outputs. Currently I have set up my flow and that gets me an object with multiple key-value pairs such as 'id', 's', 'r', 'v' and 't' as keys and their respective values as I inject the node.

Example output after inject :

"{"readResults":[{"id":"AB.CMM.Prgm_MainProgram.f_ten_point_avg_left_camber","s":true,"r":"","v":0.0261451192,"t":1657888956310}]}"

Now what my goal is to get only the "v" key's value in the msg.payload so as an example when I inject it should only give me 0.261451192 if considering the above object.

I have created a function node and following is my super simple code which I tried to get the expected output but it was not successful.

var newMsg = { payload: msg.payload[5] };
return newMsg;

Please note I'm super new to Node-RED and trying to learn as I go and really appreciate your help and guidance.

I've tried to explain the question in-detail but if anyone does not follow me I hope the following figure will give you a better idea. Thank you very much!

enter image description here


Solution

  • It looks like you have set the HTTP-request node to output a a UTF-8 String rather than a JSON object. So using array style notation (object[2]) will just return the character at that offset into the string.

    The correct thing to do is to change the output type at the bottom of the HTTP-request config to a parsed JSON Object which will mean you can then access values by their keys. e.g. msg.payload.v or msg.payload['v'].

    The other option is to pass the message through an instance of the JSON node which will convert Strings to Objects or Objects to Strings depending on the format of the input messages.