diff --git a/esphome/components/json/json_util.cpp b/esphome/components/json/json_util.cpp index dbdf6e3486..869d29f92e 100644 --- a/esphome/components/json/json_util.cpp +++ b/esphome/components/json/json_util.cpp @@ -8,6 +8,13 @@ namespace json { static const char *const TAG = "json"; +#ifdef USE_PSRAM +// Global allocator that outlives all JsonDocuments returned by parse_json() +// This prevents dangling pointer issues when JsonDocuments are returned from functions +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) - Must be mutable for ArduinoJson::Allocator +static SpiRamAllocator global_json_allocator; +#endif + std::string build_json(const json_build_t &f) { // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson JsonBuilder builder; @@ -33,8 +40,7 @@ JsonDocument parse_json(const uint8_t *data, size_t len) { return JsonObject(); // return unbound object } #ifdef USE_PSRAM - auto doc_allocator = SpiRamAllocator(); - JsonDocument json_document(&doc_allocator); + JsonDocument json_document(&global_json_allocator); #else JsonDocument json_document; #endif