.value("key", default) 是否不适用于空 json 对象?
Does .value("key", default) not work with empty json objects?
我 运行 在使用 nlohmann/json
库中的 value
函数时遇到了一些麻烦。我有一个空的 json 对象,如果嵌套键已初始化,我想对其进行初始化或递增。我一直在尝试使用值函数来解决这个问题,但我一直 运行ning 进入错误:
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;
}
它不适用于非对象 json 值,默认构造函数表示 null
,而不是 {}
。
来自他们的 documentation value()
:
Exceptions
- type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
您必须使用 nlohmann::json(json::value_t::object)
或其他方式初始化每个对象,以将其初始化为空的 object.
我 运行 在使用 nlohmann/json
库中的 value
函数时遇到了一些麻烦。我有一个空的 json 对象,如果嵌套键已初始化,我想对其进行初始化或递增。我一直在尝试使用值函数来解决这个问题,但我一直 运行ning 进入错误:
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;
}
它不适用于非对象 json 值,默认构造函数表示 null
,而不是 {}
。
来自他们的 documentation value()
:
Exceptions
- type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.
您必须使用 nlohmann::json(json::value_t::object)
或其他方式初始化每个对象,以将其初始化为空的 object.