How to pass variables values to Function node?

#1

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!

0 Likes

#2

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?

0 Likes

#3

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!

0 Likes

#4

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

#5

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

0 Likes

#6

Oops - I missed a comma after msg.click.

0 Likes

#7

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!

0 Likes

#8

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

0 Likes

#9

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

0 Likes

#10

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

0 Likes