0

我在使用库中的value函数时遇到了一些障碍nlohmann/json。我有一个空的 json 对象,如果嵌套键被初始化,我想初始化它或增加它。我一直在尝试使用 value 函数来解决这个问题,但我一直遇到错误:

C++ exception with description "[json.exception.type_error.306] cannot use value() with null" thrown in the test body.

那么,这行不通吗?

nlohmann::json json;
std::string i = "1", j = "2", k = "3";
int old_value = json.value(i, nlohmann::json())
                    .value(j, nlohmann::json())
                    .value(k, 0);
json[i][j][k] = old_value + 1;

编辑:对于那些想要更好的方法来做这类事情的人,我找到了更好的方法。

try {
    json[i][j][k].get_ref<nlohmann::json::number_integer_t &>()++;
} catch (nlohmann::json::type_error & ex) {
    json[i][j][k] = 1;
}
4

1 回答 1

2

它不适用于非对象 json 值,并且默认构造函数表示null, not {}

从他们的文档value()

例外

  • type_error.306 如果 JSON 值不是对象;在这种情况下,将 value() 与键一起使用是没有意义的。

您必须使用nlohmann::json(json::value_t::object)或其他东西初始化每个对象以将其初始化为空对象

于 2020-01-16T03:30:05.077 回答