Skip to content

Commit

Permalink
fix: handle numeric values disguised as strings in JSON
Browse files Browse the repository at this point in the history
closes #1104.
  • Loading branch information
schlimmchen committed Jul 15, 2024
1 parent b90da21 commit 9e7a0bc
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions src/Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,24 @@ void Utils::removeAllFiles()
}

/* OpenDTU-OnBatter-specific utils go here: */
template<typename T>
std::optional<T> getFromString(char const* val);

template<>
std::optional<float> getFromString(char const* val)
{
float res = 0;

try {
res = std::stof(val);
}
catch (std::invalid_argument const& e) {
return std::nullopt;
}

return res;
}

template<typename T>
std::pair<T, String> Utils::getJsonValueByPath(JsonDocument const& root, String const& path)
{
Expand Down Expand Up @@ -156,13 +174,24 @@ std::pair<T, String> Utils::getJsonValueByPath(JsonDocument const& root, String
return { T(), String(errBuffer) };
}

if (!value.is<T>()) {
if (value.is<T>()) {
return { value.as<T>(), "" };
}

if (!value.is<char const*>()) {
snprintf(errBuffer, kErrBufferSize, "Value '%s' at JSON path '%s' is not "
"of the expected type", value.as<String>().c_str(), path.c_str());
return { T(), String(errBuffer) };
}

return { value.as<T>(), "" };
auto res = getFromString<T>(value.as<char const*>());
if (!res.has_value()) {
snprintf(errBuffer, kErrBufferSize, "String '%s' at JSON path '%s' cannot "
"be converted to the expected type", value.as<String>().c_str(), path.c_str());
return { T(), String(errBuffer) };
}

return { *res, "" };
}

template std::pair<float, String> Utils::getJsonValueByPath(JsonDocument const& root, String const& path);

0 comments on commit 9e7a0bc

Please sign in to comment.