Problems extracting json using esphome

Hi,
I am very new to esphome and need a little help. I am trying to extract some data from a json api for temperature but I am having some issues. here is my code:

- http_request.get:
    url: http://api.open-meteo.com/v1/forecast?latitude=0.00&longitude=0.00&current=temperature_2m,wind_speed_10m
    capture_response: true
    on_response:
           then:
             - lambda: |-
                   json::parse_json(body, [](JsonObject root) -> bool {
                   id(temp_test).publish_state(root["current"]["temperature_2m"]);
                   return true;
                   });

when I flash my device (guition esp32-s3-4848s040) I get an error in the logs…

“Could not allocate memory for JSON document! Requested 0 bytes, free heap: 6291456”

here is what the json looks like

{
  "latitude": 0,
  "longitude": 0,
  "generationtime_ms": 0.023961067199707,
  "utc_offset_seconds": 0,
  "timezone": "GMT",
  "timezone_abbreviation": "GMT",
  "elevation": 0,
  "current_units": {
    "time": "iso8601",
    "interval": "seconds",
    "temperature_2m": "°C",
    "wind_speed_10m": "km/h"
  },
  "current": {
    "time": "2024-09-30T14:45",
    "interval": 900,
    "temperature_2m": 25.2,
    "wind_speed_10m": 13.7
  }
}

If I try the same code but for a different website (http://wasab.is/json) which I saw on another post and I request (root[“latitude”) then I get no errors and temp_test is populated correctly.

Any help gratefully received !
Thanks
Russ

Is it because the response is “chunked” ?

I seem to remember I had a problem (a year or more ago) with json::parse_json() when trying to grab more than one level down. Try this:

- lambda: |-
    json::parse_json(body, [](JsonObject root) -> bool {
      if (root.containsKey("current")) {
        JsonObject current = root["current"];
        if (current.containsKey("temperature_2m") {
          id(temp_test).publish_state(current["temperature_2m"]);
          return true;
        }
      }
      return false;
    });

It’s not pretty or convenient, but it might work! It might be a casting thing, so perhaps

id(temp_test).publish_state(((JsonObject) root["current"])["temperature_2m"])

would also work, but I’m not sure of the syntax for casting in C++.

Thanks for replying …
I still couldn’t get open-meteo to respond without errors in the log. I have see some other discussions that it might be because the response is chunked and so doesn’t have a content length.

I gave up in the end and got a text value back from another website.