Search code examples
javascriptjsondoublenode-red

Node-Red: Parse JavaScript Object with Double value


I am using node-RED to call in data from a robot. In the debug window it says it is a 'msg: Object', and when I copy it to a notepad it takes the format: {"topic":"","payload":27.659992218017578,"_session":{"type":"tcp","id":"0151ff7339437ec6"},"_msgid":"6a6897605a523366"}

I am also not sure if this is a JSON object or not, as I see examples with '' around the brackets.

I am trying to use the function node within node-red to parse this to attain the "payload" value. However, it keeps returning as undefined.

I am using the script:

var json =msg.payload;
var obj = JSON.parse(json);
msg.payload = console.log(obj.payload);
return msg;

I am a beginner to javascript and JSON, however I have tried searching and all examples only have integers as the parsing value. I am also unsure if the value name itself 'payload' is causing an issue. I have also attempted to stringify and using 'getDouble' but had no luck, which I owe to my lack of experience.

I appreciate any guidance.


Solution

  • After the node that gets the above information (the data in {} in the question}, I then used the function node to construct the message that I wanted to sent to the IIOT platform. I did

    const str = msg.payload
    msg.payload = " ," + str
    // where the text I required was in " "
    return msg
    

    Also this works:

    msg.payload = ","  + msg.payload
    return msg
    

    And then I used the MQTT output node to publish this to the IIOT platform