我在使用库中的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;
}