Search code examples
c++nlohmann-json

Does .value("key", default) not work with empty json objects?


I've run into a bit of a snag using the value function in the nlohmann/json library. I have an empty json object and I want to either initialize it or increment it if the nested keys are initialized. I've been trying to solve this problem using the value function, but I keep running into the error:

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

So, would this just not work?

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;

Edit: For those that want a better way to do this sort of thing, I've found a better way.

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

Solution

  • It does not work for non-object json values, and the default constructor represents null, not {}.

    From their documentation for value():

    Exceptions

    • type_error.306 if the JSON value is not an object; in that case, using value() with a key makes no sense.

    You'll have to initialize each one with nlohmann::json(json::value_t::object) or something else to initialize it to an empty object.