Help substituting value

#1

I have a function node with the following :

msg.payload='{"state":"ON","brightness":250,"color_temp":250,"bulb_mode":"white","color":{"r":255,"g":255,"b":255}}';
return msg;

It works fine but I am totally stumped, how do I substitute "brightness":250 to "brightness": 'a value' contained in the incoming msg payload ? like if I inject 100 into the function node the output should = "brightness":100

0 Likes

#2

Heeey, i think you should try something like this:

var inconming = msg.payload;
msg.payload='{"state":"ON","brightness":incoming,"color_temp":250,"bulb_mode":"white","color":{"r":255,"g":255,"b":255}}';
return msg;

pd: taking msg.payload as an integer, otherwise you must use parseInt()
Regards!.

0 Likes

#3

If your intent is to return a JSON string then you will have to concatenate the incoming payload into the middle of the string using the JS concatenate operator + like so:

msg.payload = '{"state":"ON","brightness":' + msg.payload + ', "color_temp": 250, "bulb_mode": "white", "color": { "r": 255, "g": 255, "b": 255 } }';

which would more simply be done with a template node, configured like so:

image

On the other hand, if your intention is to create a payload object then the JS syntax is:

msg.payload = {
    "state": "ON",
    "brightness": +msg.payload,
    "color_temp": 250,
    "bulb_mode": "white",
    "color": {
        "r": 255,
        "g": 255,
        "b": 255
    }
};
return msg;

which you can also accomplish by checking the "Output as Parsed JSON" on the change node above.

0 Likes

#4

Thanks shrickus your first solution works perfectly for me (I swear I tried this solution about 4 hours ago but obviously I must have made some mistake) anyway I can now move on thanks again.

0 Likes