Extracting json from mqtt?

Hi,

I have a text sensor that subscribes to a topic which is formatted in json.

I want to pull out one pair of data and add that value to a sensor in esphome.

Is there an easy way to have this “temperature”:17.11, extracted from the json text and create a sensor called “Outside Temperature”?

I am guessing some sort of lambda is involved but thats a bit above my head!

From googling it, I can see a sensor that pulls info via http and extracts values all as part of one lambda but not sure if subscribing to mqtt would work the same.

Thanks

Would something like this work ?

    - state_topic: "your state topic"  
      name: "Outside Temperature"
      unit_of_measurement: "°C"
      unique_id: outside temperature
      value_template: '{{ value_json.temperature }}' 

Print your JSON the whole thing including the curly barckets and someone might have a crack at it.

There is a json component which uses ArduinoJson (although it works fine with ESP-IDF also).
With that, you will need a bit of a lambda, but it’s quite simple.
Something like this:

json:

text_sensor:
  - id: your_text_sensor_with_json_value
    platform: the_platform_of_your_sensor
    ...
    on_value:
      then:
        - lambda: |-
            DynamicJsonDocument json(1024);
            DeserializationError error = deserializeJson(json, x.c_str());
            if (error) {
              ESP_LOGE("your_tag", "Error parsing json: %s", x.c_str());
              ESP_LOGE("your_tag", "Error: %s", error.c_str());
            } else {
              const float temperature = json["temperature"].as<float>();
              id(outside_temperature).publish_state(temperature);
            }

That’s the geat thing about HA , there is more than one way of doing things usually.

1 Like