How to pull a variable from an array in payload

Hi all

Hoping someone can help me. I am trying to pull sensor information from a device (MQTT), but having trouble extracting just what I need from the payload.

Debug output looks like this:

7/13/2022, 10:24:01 AM
node: 0c1ee5723f948408meraki/v1/mt/L_585467951558182753/ble/{DeviceMAC}/temperature : msg : Object

object >
topic: "meraki/v1/mt/L_585467951558182753/ble/{DeviceMAC}/temperature"
payload: "{"ts":"2022-07-13T08:16:37Z","fahrenheit":75.5,"celsius":24.2}"
qos: 0
retain: true
_msgid: "f62fd05586202cef"

When I go to extract "fahrenheit":75.5, I try to do it like this:
msg.payload[1] but that only seems to get me """, msg.payload[2] is "t", msg.payload[3] is "s", so it seems that the payload is not an actual array, it seems to be reading it as a string?. Does that make sense?

Any ideas how I can extract any of those 3 values? (timestamp, F, C)

In this case msg.payload is an object (objects are surrounded by curly braces {}), not an array (arrays are surrounded by brackets []). You can access them like msg.payload.ts or msg.payload.fahrenheit rather than msg.payload[X]

msg.payload could also be a JSON string, in which case you would need to convert it into an object first.

Use the built in tools provided...

There’s a great page in the docs (Working with messages : Node-RED) that will explain how to use the debug panel to find the right path to any data item.

Pay particular attention to the part about the buttons that appear under your mouse pointer when you over hover a debug message property in the sidebar.

BX00Cy7yHi

2 Likes

Thank you for your reply. Sorry, forgot to mention that I had tried that but I get undefined in the debug output

Yeah I think I do need to convert it to an object first, let me figure that out and see what I get

It looks like payload is a string.

Are you outputting an object from the mqtt node? If not select output a parse object in the mqtt node config.
Then fahrenheit will be an object property, You will then access it at msg.payload.fahrenheit

1 Like

Great callout! Didnt even think to look at what my mqtt node was configured as, it was set to automatic (string or buffer)
I changed it to JSON object, and now I can call on it using msg.payload.fahrenheit

Thank you all for your help and guidance! As you can tell, I am a newbie, but love learning new things :slight_smile:

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.