How to split JSON data into two sensors

Hello everyone, i’m trying to read data from a dht sensor connected to an arduino. I get a valid JSON data but i have no idea how to split it into two different sensors in hass.

This is what i did so far:

sensor:
  - platform: serial
    serial_port: /dev/ttyUSB0
    baudrate: 115200
    value_template: "{{value_json}}"

  - platform: template
    sensors:
      my_temperature_sensor:
        friendly_name: Temperature
        unit_of_measurement: "°C"
        value_template: "{{ value_json.temperature }}"
      my_humidity_sensor:
        friendly_name: Humidity
        unit_of_measurement: "%"
        value_template: "{{ value_json.humidity }}"

can you help me? thanks :sweat_smile:

@dylan96 I’ve only done this for a DHT11 connected to a sonoff as an MQTT sensor but this may still work for yours…

  - platform: mqtt
    state_topic: "tele/sonoff17/SENSOR"
    name: "Rumpus Temperature"
    unit_of_measurement: "°C" 
    value_template: "{{ value_json.DHT11.Temperature }}"

  - platform: mqtt
    state_topic: "tele/sonoff17/SENSOR"
    name: "Rumpus Humidity"
    unit_of_measurement: "RH%" 
    value_template: "{{ value_json.DHT11.Humidity }}"

Hope that helps for your case?

Unfortunately value_json data does not transfer from a state. It get’s turned into a string. Personally, If I were you, i’d do the following:

sensor:
  - platform: serial
    name: serial_temp_and_hum
    serial_port: /dev/ttyUSB0
    baudrate: 115200
    value_template: "{{ value_json.temperature }},{{ value_json.humidity }}"

  - platform: template
    sensors:
      my_temperature_sensor:
        friendly_name: Temperature
        unit_of_measurement: "°C"
        value_template: "{{ states('sensor.serial_temp_and_hum').split(',')[0] | float }}"
      my_humidity_sensor:
        friendly_name: Humidity
        unit_of_measurement: "%"
        value_template: "{{ states('sensor.serial_temp_and_hum').split(',')[-1] | float }}"

This will only have 1 serial call for 2 sensors. And you’ll easily split out the data without needing to use regex. Basically, what we are doing is making a comma separated state with temperature,humidity. Then in the template sensor we split on the comma and get the first item ([0] temperature), and the last item ([-1] humidity)

1 Like

Thank you this is exactly what I was looking for!

1 Like