How to pass variables values to Function node?

Hi,

I need to use this pass these values in a Function node:

msg.payload = '[{ "time”:”TIMESTAMP”,”entity": "entity1", "type": "living_room", "state": “STATE_VALUE”, "value": "2", "location":"bedroom" }]';
return msg;

All values in capital letters have to be replaced with the actual values from the previous node. I tried using this, but it won't work:

msg.payload = '[{ "time”:”TIMESTAMP”,”entity": "entity1", "type": "living_room", "state": “{{{click}}}”, "value": "2", "location":"bedroom" }]';
return msg;

Previous node is setup this way:
org%202019-02-15%2022-19-09

Any ideas? Also, any way to get the timestamp on that?

Thanks!

Hi @Traste

You say all the properties in capital letters need to be replaced, I can see TIMEZONE STATE_VALUE and VALUE - what are the properties of the message you are passing the function that contain those values? msg.payload.TIMEZONE? or something else?

Thanks for replying. So sorry, but I just noticed I did not paste it the data properly. I wanted to write "timestamp" instead of timezone, and only 1 variable more. I edited my message :sweat_smile:

So, I need:

  • TIMESTAMP: a way to add the current time with the timestamp format
  • STATE_VALUE: I get this value from the previous node, from msg.click, as per my image

Thanks!

As you want it to be a JSON String, the easiest way to create the string is to create the javascript object and then convert it to JSON.

var myObject = [
    {
        "time": Date.now(),
        "entity": "entity1",
        "type": "living_room",
        "state": msg.click
        "value": "2",
        "location": "bedroom"
    }
];
msg.payload JSON.stringify(myObject);
return msg;

You haven't said anything about the required format of the timestamp - I've used Date.now() to get the current time in milliseconds since epoch. If you need a different format, that are countless examples of generating timestamps in JavaScript using the Date object.

1 Like

That really does sound great! Although I'm getting some kind of syntax error. Sorry, I'm new to coding :-/

org%202019-02-15%2022-53-06

Oops - I missed a comma after msg.click.

Thanks! I got it working with this syntax:

var myObject = [
    {
        "time": new Date().toISOString(),
        "entity": "entity1",
        "type": "living_room",
        "state": msg.click,
        "value": "2",
        "location": "bedroom"
    }
];
msg.payload= JSON.stringify(myObject);
return msg;

You made my day!

As I said, thanks a million!

I would be interested to know why you want it as a JSON string rather than a js object.

I'm using the BigQuery insert node, and that's the output format it needs :slight_smile:

I see you are right, how unusual, normally one would expect to pass in an object not a json string.