ESPhome how to read json from web?

Hello. I would like to make esphome sensor independent on Home Assistant in that it reads weather forecast from openweathermap and controls some switches (roolls up exterior blinds if wind is coming).

I can read forecast by http_request.get and it is in JSON, XML or HTTP format. Can I convert from these formats to variables in esphome, or do I need to do it in C++ lambda?

Thanks, Jan

Paste the response that you’re getting here and we’ll have a shot. Use the preformatted text button in the editor when posting code.

{"your code": "should end up looking like this"}

{“not”: “like this”}

Thanks. The response looks like this, forecast is in section “weather” and I am looking for value “list.wind.speed”:

{"cod":"200","message":0,"cnt":1,"list":[{"dt":1619805600,"main":{"temp":287.83,"feels_like":286.5,"temp_min":284.84,"temp_max":287.83,"pressure":1010,"sea_level":1010,"grnd_level":987,"humidity":44,"temp_kf":2.99},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"clouds":{"all":24},"wind":{"speed":4.43,"deg":18,"gust":8.14},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2021-04-30 18:00:00"}],"city":{"id":3067696,"name":"Prague","coord":{"lat":50.088,"lon":14.4208},"country":"CZ","population":1165581,"timezone":7200,"sunrise":1619753998,"sunset":1619806732}}

Solved it! Following code works. It finds third forecast of hourly wind speed, which is 1-2 hours ahead of current time:

(please note that I was getting some crashes on ESP8266, but not on ESP32. Seems to be memory problem)

sensor:
  - platform: template
    name: "Predicted wind"
    id: predicted_wind

http_request:
  useragent: esphome/device
  timeout: 10s

time:
  - platform: sntp
    on_time:
      - seconds: 0
        minutes: /15
        then:
          - lambda: |-
              HTTPClient http;
              http.begin("http://api.openweathermap.org/data/2.5/onecall?lat=51&lon=14&appid=974---------------8c0d&lang=cz&exclude=minutely,daily,alerts");
              http.GET();
              DynamicJsonBuffer doc(31000); //cannot be smaller, response is big!
              JsonObject& root = doc.parseObject(http.getStream());
              float ws = atof(root["hourly"][2]["wind_speed"].as<char*>());
              id(predicted_wind).publish_state(ws);
              //ESP_LOGD("main", "############## %s", root["hourly"][2]["wind_speed"].as<char*>()); //.as<char*>());
3 Likes

Great job! These little devices really can do a lot, can’t they?

Is this code up to date with the last version? I’m getting an error

esphome.yaml:119:7: error: 'HTTPClient' was not declared in this scope

Do you have this declaration in yaml?

http_request:
  useragent: esphome/device
  timeout: 5s #30s