Convert object to string

5,477 views
Skip to first unread message

Deepak Raja

unread,
Aug 27, 2015, 5:04:06 AM8/27/15
to Node-RED
Hi,
      I am trying to parse a object into string in template node using a javascript code.It is a url which i need to use to display images according some change in sensor.When i print it ,the link is passed as payload,which is object format,which could not be used as string for the template node.So,please provide me some insight how to solve this .I have added my both function node and template node code below.I have attached the flow node image and screenshot of my debug node output,where the link is visible and also the code for both my function node and template node.

Function Node code:

ad = "";

var objecttemp=msg.payload.d.object_temp;
if(objecttemp<=11 )
{
   i=1;
   msg.topic="IBAROUND CONTEXTUAL AD"
   sampletext="Its too cold.Swedish Winter sucks!!How about a hot soup to calm you down?.Check out your personalised discount coupon --->"
   msg.payload = ad;
   temp = objecttemp;
}
else if(objecttemp>=30)
{
   i=2;
   msg.topic="IBAROUND CONTEXTUAL AD"
   sampletext="Its freaking hot outside.How about having one of your favouirte magnum flavour ? Check out your personalised discount coupon ---> "
   msg.payload = ad;
   temp = objecttemp;
}
else
{
    i=0;
    msg.topic="IBAROUND CONTEXTUAL AD"
    msg.payload= ad;
}
return msg ;


Template Node code:

<!DOCTYPE html>
<html>
   <head>
      <title>IBAROUND CONTEXTUAL MARKETING</title>
      <script type = "text/javascript">
         function displayad()
         {
             
             document.getElementById("img").src = "{{{payload}}}"; 
         }
         function startTimer()
          {
              setInterval(displayad,3000);
          }
      </script>
   </head>
   
   <body onload="startTimer()">
   </body>
</html>


Entire flow of the nodes(Entire code flow):

[{"id":"e15c2a9b.1ea3d8","type":"websocket-listener","path":"/addisplay14","wholemsg":"false"},{"id":"35413efd.cabec2","type":"ibmiot","name":"tisensortag"},{"id":"bcdb3498.4324c8","type":"ibmiot in","authentication":"quickstart","apiKey":"35413efd.cabec2","inputType":"evt","deviceId":"5c313ebff128","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"sensor tag cc2540","service":"quickstart","allDevices":"","allApplications":"","allDeviceTypes":true,"allEvents":true,"allCommands":"","allFormats":"","x":87,"y":391,"z":"631a9bdb.9ce564","wires":[["5905a4f7.a6fa5c","2439cd51.dbc632","9b433532.64bcc8"]]},{"id":"9b433532.64bcc8","type":"function","name":"","func":"i=0;\ntemp=0;\nad = \"\";\n\nvar objecttemp=msg.payload.d.object_temp;\nif(objecttemp<=11 )\n{\n   i=1;\n   ad = \"https://lh3.googleusercontent.com/e0w-tC7Zq2iJz3vNbkJ8G1mrc1HKiEumixeF3q_xEQ=w528-h562-no\"\n   msg.topic=\"IBAROUND CONTEXTUAL AD\"\n   sampletext=\"Its too cold.Swedish Winter sucks!!How about a hot soup to calm you down?.Check out your personalised discount coupon --->\"\n   msg.payload = ad;\n   temp = objecttemp;\n}\nelse if(objecttemp>=30)\n{\n   i=2;\n   ad = \"https://lh3.googleusercontent.com/i5qJucn2DaxJf6QENOotl6NGuUH-Kq26jmvpn4JEjg=w528-h562-no\"\n   msg.topic=\"IBAROUND CONTEXTUAL AD\"\n   sampletext=\"Its freaking hot outside.How about having one of your favouirte magnum flavour ? Check out your personalised discount coupon ---> \"\n   msg.payload = ad;\n   temp = objecttemp;\n}\nelse\n{\n    i=0;\n    msg.topic=\"IBAROUND CONTEXTUAL AD\"\n    ad = \"https://lh3.googleusercontent.com/MbS8rAifpson5yuYTa5MHbbVENGNF192n6P6UbMeqQ=w528-h562-no\"\n    msg.payload= ad;\n}\nreturn msg ;","outputs":"1","noerr":0,"x":331,"y":395,"z":"631a9bdb.9ce564","wires":[["fa40bb9b.05bf48"]]},{"id":"8488e9d7.7b7718","type":"http in","name":"addisps","url":"/addisplay14","method":"get","swaggerDoc":"","x":60,"y":527,"z":"631a9bdb.9ce564","wires":[["fa40bb9b.05bf48"]]},{"id":"fa40bb9b.05bf48","type":"template","name":"Default","field":"payload","format":"handlebars","template":"<!DOCTYPE html>\n<html>\n   <head>\n      <title>IBAROUND CONTEXTUAL MARKETING</title>\n      <script type = \"text/javascript\">\n         function displayad()\n         {\n             \n             document.getElementById(\"img\").src = \"{{{payload}}}\"; \n         }\n         function startTimer()\n          {\n              setInterval(displayad,3000);\n          }\n      </script>\n   </head>\n   \n   <body onload=\"startTimer()\">\n        <img id=\"img\" src=\"https://lh3.googleusercontent.com/MbS8rAifpson5yuYTa5MHbbVENGNF192n6P6UbMeqQ=w528-h562-no\" height=600 width=400 />\n   </body>\n</html>","x":304.89581298828125,"y":526.8888854980469,"z":"631a9bdb.9ce564","wires":[["fa887fd1.05778","2e5a6814.d1a598"]]},{"id":"2e5a6814.d1a598","type":"http response","name":"addisps","x":592,"y":461,"z":"631a9bdb.9ce564","wires":[]},{"id":"fa887fd1.05778","type":"debug","name":"Payload msg","active":true,"console":"true","complete":"payload","x":590.4513549804688,"y":586.8888854980469,"z":"631a9bdb.9ce564","wires":[]},{"id":"458118ce.ba7ee8","type":"function","name":"Display ads","func":"return msg;","outputs":"1","noerr":0,"x":279.89581298828125,"y":669.888916015625,"z":"631a9bdb.9ce564","wires":[["2c9ceb13.d36314"]]},{"id":"ab22741d.54dd88","type":"websocket in","name":"adlistener","server":"e15c2a9b.1ea3d8","client":"","x":60.5,"y":666,"z":"631a9bdb.9ce564","wires":[["458118ce.ba7ee8"]]},{"id":"2c9ceb13.d36314","type":"websocket out","name":"addisplay","server":"e15c2a9b.1ea3d8","client":"","x":598,"y":663,"z":"631a9bdb.9ce564","wires":[]}]


Please help me to fix this ,since it was proof of concept for our startup to investors in our next conference.Hoping for a positive response from your side.

Regards,
Deepak Raja

node-red flow.jpg

Mark Setrem

unread,
Aug 27, 2015, 6:28:21 AM8/27/15
to Node-RED
Looking at the image you added, and what you say your problem is I'm confused.
Are your concerns around the debug message "[msg]:string No Response Object"?

This is caused because a message that starts with at your sensor tag node ends up at a http out node.  The http out node only works if the flow starts with a http request (there has to be a http request for it to respond to).  Hence the message.

Other than that the debug message underneath that shows that the template node is adding the URL exactly as you have asked it to.



You might also want to google how cold it is in Sweden in winter.  

Deepak Raja

unread,
Aug 27, 2015, 6:47:10 AM8/27/15
to Node-RED

Hi Mark,
                 I know that the http out node works only ,if there is a http input node.Take a look at the picture file i have attached.I have inputted the http in node to the template node,which eventually outputs the url.The sensortag just takes the temperature and the function node compares the temperature and stores appropriate url in msg.payload and sends it to the template node,which parses it and sents the html to the http out node.Below flowchart will illustrate what is happening inside.



SensorTag(Temperature input) + Http in node(Get function to post the image) ----> FunctionNode(Comparision of Temperature and stores appropriate url link of image in msg.payload)----->TemplateNode(Recieves msg.payload({{{payload}}}) and parses it and creates a html file(dynamically))----->Httpout node(Displays the appropriate html image in a web browser)


Websocket in(Just to listen to the appropriate the link(/addisplay14)---->Templatenode(Nothing)--->Websocket out(Listens to the link where the above template node posts the html page)


My question is ,when the msg.payload which has the url for the image(google link) is passed from the function-node to template node in the first flowchart,the payload({{{payload}}}) received in the template node was in object format([object object]) not in string format(https://lh3.googleusercontent.com/e0w-tC7Zq2iJz3vNbkJ8G1mrc1HKiEumixeF3q_xEQ=w528-h562-n) .I tried to convert this object to string using some predefined javascript functions,which are used for the converting object to string(JSON.stringify() or JSON.parse()) ,but it does not converts that object to string.



For that part alone, i need help to figure out if there is any other predefined function to convert that object to string or is there some other way to convert the object url to string url ,which could used by the HTML file to display the image.


Hope the above explanation is clear enough to understand my issue.

P.S: FYI,I know personally how hard swedish winter is ,after living here for 5 years, so i am pretty sure about it !! :P

Mark Setrem

unread,
Aug 27, 2015, 7:16:55 AM8/27/15
to Node-RED
 There isn't a method of having 2 inputs.  So you can't have a flow that starts with

"SensorTag(Temperature input) + Http in node(Get function to post the image)"

So your flow is either:
SensorNode->Function->Template->http out which will fail as the flow hasn't started with a http in node

or

Http In Node -> Template Node -> Http Out which will fail as theres no function node or sensor value within the flow.

If you want to store data from the sensor to pick up in the http In -> http out flow you need to look at using Global.context that is in the writing functions part of the documentation.

As I sit typing this in Gøteborg I bow to your better knowledge of a Swedish winter, I would have thought that 11 degrees Celsius would have been a heatwave.

Nicholas O'Leary

unread,
Aug 27, 2015, 7:23:34 AM8/27/15
to Node-RED Mailing LIst
From the code you've shared, you are always setting msg.payload to a string - so I'm not clear in what condition you see [object object] in the template output.
And from the screenshot, the debug output suggests the url has successfully been inserted into the template.

Nick

--
http://nodered.org
---
You received this message because you are subscribed to the Google Groups "Node-RED" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-red+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Deepak Raja

unread,
Aug 27, 2015, 7:40:15 AM8/27/15
to Node-RED

@mark: Sorry for the weather thing.I respect you,but from a south- indian perspective living in stockholm for 5 years,i feel anything below 10 C is winter !! :P .Nothing offensive and sorry if it was.For the Global.Context thing,i will take a look at it and will see if i can update it.


@nicloas: I see the [object object] when there is no input comes from the sensortag,which i have attached the picture above,which shows evidently even though the function node stores the msg.payload as string ,while sending it to the template node,it converts it to somehow object,which could not be readable as string in the template node.So,i will take @mark approach to store the sensor data using Global.Context variable and send to template node,where i will compare and display the html image thing and see if it comes.

On the other hand,it would be helpful ,if you could provide some function which reconverts the object to string inside the template node ,which could be used by the html file to display the image,then my work will be reduced as well.

Hoping for a positive response from your side guys and will update the progress in few hours as well.

Regards,
Deepak Raja
node flow no sensor data.jpg

Nicholas O'Leary

unread,
Aug 27, 2015, 7:50:32 AM8/27/15
to Node-RED Mailing LIst
Deepak,

ah - I see. Mark is quite right you need to be storing the value from the sensortag somewhere, so that when your http request comes in, it can use whatever the last value from the sensortag was.

Nick

--

ValeMrt

unread,
Jan 26, 2016, 10:43:32 AM1/26/16
to Node-RED
Hi Deepak,

I found this thread 'cause I'm having exatly the same problem with node-red. I'm trying to write on the HTML page the humidity value from the sensor. It's clearly written on the debug console but on the HTML page all I get is [object Object].

This is my entire flow:
[{"id":"3fb7ef0.e635a12","type":"ibmiot","z":"d6e25523.a73f2","name":"Plant"},{"id":"3e77d543.c1882a","type":"ibmiot in","z":"d6e25523.a73f2","authentication":"quickstart","apiKey":"3fb7ef0.e635a12","inputType":"evt","deviceId":"27d58b2cc038","applicationId":"","deviceType":"+","eventType":"+","commandType":"","format":"json","name":"IBM IoT App In","service":"quickstart","allDevices":false,"allApplications":false,"allDeviceTypes":true,"allEvents":true,"allCommands":false,"allFormats":false,"x":251,"y":291,"wires":[["ae0082ac.51ff8","c0c482df.3f3b8"]]},{"id":"ae0082ac.51ff8","type":"function","z":"d6e25523.a73f2","name":"hum","func":"return {payload:msg.payload.d.humidity};","outputs":"1","noerr":0,"x":408.5,"y":353,"wires":[["ff6ad0d9.00953"]]},{"id":"ff6ad0d9.00953","type":"switch","z":"d6e25523.a73f2","name":"hum thresh","property":"payload","propertyType":"msg","rules":[{"t":"lte","v":"40","vt":"str"},{"t":"gt","v":"40","vt":"str"}],"checkall":"true","outputs":2,"x":594.5,"y":339,"wires":[["4eed0b45.1e1224"],["47c4c419.31d51c"]]},{"id":"5dad02b7.a252fc","type":"debug","z":"d6e25523.a73f2","name":"humidity level","active":true,"console":"true","complete":"payload","x":1080.5,"y":231,"wires":[]},{"id":"c0c482df.3f3b8","type":"debug","z":"d6e25523.a73f2","name":"device data","active":true,"console":"true","complete":"true","x":464.5,"y":273,"wires":[]},{"id":"9c34b7fe.066698","type":"http in","z":"d6e25523.a73f2","name":"","url":"/plant","method":"get","swaggerDoc":"","x":865,"y":509.5,"wires":[["5473cb9d.cadb0c"]]},{"id":"27f7302.15f295","type":"http response","z":"d6e25523.a73f2","name":"plant","x":1496,"y":461,"wires":[]},{"id":"f4e062d7.21044","type":"debug","z":"d6e25523.a73f2","name":"","active":true,"console":"false","complete":"payload","x":1525,"y":253,"wires":[]},{"id":"fe4e0b84.abec7","type":"template","z":"d6e25523.a73f2","name":"Page-Template","field":"payload","fieldType":"msg","template":"Hello there <br />\n\nHumidity: {{payload}}<br />","x":1270,"y":408,"wires":[["27f7302.15f295","f4e062d7.21044"]]},{"id":"4eed0b45.1e1224","type":"function","z":"d6e25523.a73f2","name":"ok","func":"\nreturn msg;","outputs":1,"noerr":0,"x":767,"y":266.5,"wires":[["5dad02b7.a252fc","5473cb9d.cadb0c"]]},{"id":"47c4c419.31d51c","type":"function","z":"d6e25523.a73f2","name":"not ok","func":"\nreturn msg;","outputs":1,"noerr":0,"x":765,"y":382.5,"wires":[["5dad02b7.a252fc","5473cb9d.cadb0c"]]},{"id":"5473cb9d.cadb0c","type":"function","z":"d6e25523.a73f2","name":"function","func":"\n//msg.payload = \"Pippo\";\n// with static 'Pippo' works!!\n\nvar mex = {payload : msg.payload};\nnode.warn(mex.payload);\n//return msg;\nreturn msg;","outputs":"1","noerr":0,"x":1056,"y":390.5,"wires":[["fe4e0b84.abec7"]]}]

ValeMrt

unread,
Jan 26, 2016, 10:46:52 AM1/26/16
to Node-RED
I also tried with global variables but still doesn't work!

Mark Setrem

unread,
Jan 26, 2016, 11:08:36 AM1/26/16
to Node-RED
So in the example you provide code for...

Your webpage calls the [http in] node.  which then goes to your [function] node that is really just a debug node, which then goes to your [template] node. which then goes to your [http out] node.
No where in the flow the webpage "sees" is there ever a msg.payload for the template node to use.

You need to think of this as 2 flows.  
The first flow captures your sensor value and stores it in a global.context object
The second flow  is the [http in] -> [Function] to pick up global context object -> [template] -> [http out]

details of global context can be found http://nodered.org/docs/writing-functions.html#global-context as the syntax depends of the version of node-red you are using.

Nicholas O'Leary

unread,
Jan 26, 2016, 11:11:26 AM1/26/16
to Node-RED Mailing List
Hi,

you need to store the humidity value somewhere as part of the flow so that when your http request comes in later on, it is able to retrieve the latest value and display it.

Something like this might help:

1. change your hum function to return the existing message object, just with its payload changed:
    msg.payload = msg.payload.d.humidity;
    return msg;

2. change your last function node to:

if (msg.topic) {
    // this message came from IoTF - it's a new reading to store
    // this is why the hum function needed to return the original message - so msg.topic would be preserved

    // store the value in local context
    context.humidity = msg.payload;
    // don't send anything on
    return;
}

// At this point, it must be an HTTP request, so set msg.payload:
msg.payload = context.humidity;
return msg;


3. done


Reply all
Reply to author
Forward
0 new messages