Convertion spdlog::level::level_enum to/from nlohmann::json

104 views Asked by At

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

1

There are 1 answers

2
Alan Birtles On

See the statement in the documentation you linked to:

NLOHMANN_JSON_SERIALIZE_ENUM() MUST be declared in your enum type's namespace (which can be the global namespace), or the library will not be able to locate it, and it will default to integer serialization.

Moving NLOHMANN_JSON_SERIALIZE_ENUM into the spdlog namespace fixes the problem:

namespace spdlog::level {
    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"}
    })
}

https://godbolt.org/z/ozWq3xT83