Extracting specific data from string

I receive a string of data from my sensor via MQTT but I do not know how to retrieve a specific variable (e.g. temperature) from the string.

From the debug window:
msg.payload : string[323]
{'data_format': 10, 'humidity': 66.0, 'temperature': 21.6, 'pressure': 1002.83, 'acceleration_total': 0.005, 'acceleration_x': 0.003, 'acceleration_y': 0.004, 'acceleration_z': 0.0, 'v_bat': 3.199, 'v_cap': 0.0, 'rspi': 0.0, 'mic': 46, 'freq': 1.0, 'counter': 228, 'dropPackets': 194, 'time': '2021-02-16T08:22:22:866734Z'}

I often use the JSON converter and simply set my message to msg.payload.temperature and I will be able to get the temperature data. However, now there is an error when I use the converter or the payload is undefined without the JSON converter. Please help!

That JSON is invalid - should be double quotes around property names (there are many online JSON validators you can test it on)

The question is, are you in control of the data being sent? If so, change all the single quotes to double quotes and it WILL be valid JSON.

If not, then you will need to hack it (search and replace all single quotes for double quotes)

1 Like


You can use the 'string' node (node-red-contrib-string) to change from single quote to double quote.



1 Like

Yeah got it, thanks!

The 'string' node is very useful. Thanks!

Changing the string at the destination is a hack. Fixing the JSON at source is the better option.

PS, the string node is a waste of space, a function node and a one-liner (or even a change node) could easily have hacked up the string into valid JSON - i didn't mention it because it wasn't the "right thing to do"

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