With the help of this tutorial from nlohmann-json's documentation, I tried to convert a key-value pair from a JSON string to spdlog::level::level_enum
.
With the following JSON
{
"log-level": "info",
"log-path": "/var/log/info/"
}
and C++ code
#include "spdlog/spdlog.h"
#include "nlohmann/json.hpp"
NLOHMANN_JSON_SERIALIZE_ENUM(spdlog::level::level_enum, {
{spdlog::level::level_enum::trace, "trace"},
{spdlog::level::level_enum::debug, "debug"},
{spdlog::level::level_enum::info, "info"},
{spdlog::level::level_enum::warn, "warn"},
{spdlog::level::level_enum::err, "err"},
{spdlog::level::level_enum::critical, "critical"},
{spdlog::level::level_enum::off, "off"}
})
int main()
{
std::string input = R"({
"log-level": "info",
"log-path": "/var/log/info/"
}
)";
auto json = nlohmann::json::parse(input);
json["log-level"]. template get<spdlog::level::level_enum>();
}
, I tried to convert the value of "log-level"
(which is "info"
) to spdlog::level::level_enum
But I got this error:
terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error'
what(): [json.exception.type_error.302] type must be number, but is object
Can someone tell me what I'm doing wrong and how I can convert "log-level": "some-spdlog-level"
to spdlog::level::level_enum
?
Thanks
See the statement in the documentation you linked to:
Moving
NLOHMANN_JSON_SERIALIZE_ENUM
into the spdlog namespace fixes the problem:https://godbolt.org/z/ozWq3xT83