Carriage returns in MQTT publish causing remote decode issues?

I’ve got a weather automation using Met Office data, which I’m trying to send out via MQTT to use elsewhere on my network.

The automation action is set up like this:

- data:
      topic: metweather/weather
      retain: true
      qos: "0"
      payload: >-
        {  "condition": {{states('sensor.london_gatwick_airport_weather_daily')|
        string }}, 
           "temperature": {{states('sensor.london_gatwick_airport_temperature_daily') | string }},
           "feels_like": {{states('sensor.london_gatwick_airport_feels_like_temperature_daily') | string }},
           "visibility": {{states('sensor.london_gatwick_airport_visibility_daily') | string }},
           "wind_speed": {{states('sensor.london_gatwick_airport_wind_speed_daily') | string }},
           "wind_dir": {{states('sensor.london_gatwick_airport_wind_direction_daily') | string }},
           "wind_gust": {{states('sensor.london_gatwick_airport_wind_gust_daily') | string }} 
        }
    action: mqtt.publish

It works, but at the far end I’m receiving this:

b'{"condition": rainy, \n "temperature": 16,\n "feels_like": 14,\n "visibility": Good,\n "wind_speed": 9,\n "wind_dir": WSW,\n "wind_gust": 11 \n}'

At the far end, i’m trying to decode it with (Python 3.9):

weather = json.loads(msg.payload.decode('utf-8'))

and it looks to be choking on the carriage returns.
Is there any way to publish the json in a format that the remote Python code will accept and decode properly?

I’ve tried to put everything in one line but it doesn’t seem to help, as I guess somewhere underneath HA is breaking the line down?

- variables:
    msg:
      condition: "{{ states('sensor.london_gatwick_airport_weather_daily') }}"
      temperature: "{{ states('sensor.london_gatwick_airport_temperature_daily') }}"
      feels_like: "{{ states('sensor.london_gatwick_airport_feels_like_temperature_daily') }}"
      visibility: "{{ states('sensor.london_gatwick_airport_visibility_daily') }}"
      wind_speed: "{{ states('sensor.london_gatwick_airport_wind_speed_daily') }}"
      wind_dir: "{{ states('sensor.london_gatwick_airport_wind_direction_daily') }}"
      wind_gust: "{{ states('sensor.london_gatwick_airport_wind_gust_daily') }}" 
- action: mqtt.publish
  data:
    topic: metweather/weather
    retain: true
    qos: "0"
    payload: "{{ msg | to_json }}"

Simple when you know how :smiley:

Many thanks, as ever.

1 Like