ESPHome 2025.10.0-dev
Loading...
Searching...
No Matches
json_util.cpp
Go to the documentation of this file.
1#include "json_util.h"
2#include "esphome/core/log.h"
3
4// ArduinoJson::Allocator is included via ArduinoJson.h in json_util.h
5
6namespace esphome {
7namespace json {
8
9static const char *const TAG = "json";
10
11std::string build_json(const json_build_t &f) {
12 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
13 JsonBuilder builder;
14 JsonObject root = builder.root();
15 f(root);
16 return builder.serialize();
17 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
18}
19
20bool parse_json(const std::string &data, const json_parse_t &f) {
21 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
22 JsonDocument doc = parse_json(data);
23 if (doc.overflowed() || doc.isNull())
24 return false;
25 return f(doc.as<JsonObject>());
26 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
27}
28
29JsonDocument parse_json(const std::string &data) {
30 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
31#ifdef USE_PSRAM
32 auto doc_allocator = SpiRamAllocator();
33 JsonDocument json_document(&doc_allocator);
34#else
35 JsonDocument json_document;
36#endif
37 if (json_document.overflowed()) {
38 ESP_LOGE(TAG, "Could not allocate memory for JSON document!");
39 return JsonObject(); // return unbound object
40 }
41 DeserializationError err = deserializeJson(json_document, data);
42
43 if (err == DeserializationError::Ok) {
44 return json_document;
45 } else if (err == DeserializationError::NoMemory) {
46 ESP_LOGE(TAG, "Can not allocate more memory for deserialization. Consider making source string smaller");
47 return JsonObject(); // return unbound object
48 }
49 ESP_LOGE(TAG, "Parse error: %s", err.c_str());
50 return JsonObject(); // return unbound object
51 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
52}
53
55 if (doc_.overflowed()) {
56 ESP_LOGE(TAG, "JSON document overflow");
57 return "{}";
58 }
59 std::string output;
60 serializeJson(doc_, output);
61 return output;
62}
63
64} // namespace json
65} // namespace esphome
Builder class for creating JSON documents without lambdas.
Definition json_util.h:56
std::function< void(JsonObject)> json_build_t
Callback function typedef for building JsonObjects.
Definition json_util.h:45
bool parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
Definition json_util.cpp:20
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
Definition json_util.cpp:11
std::function< bool(JsonObject)> json_parse_t
Callback function typedef for parsing JsonObjects.
Definition json_util.h:42
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7