Skip to content

About value(key, default_value) and operator[](key)  #1358

@oyoungs

Description

@oyoungs

When I use a json object(it may be object or null), I want to use the interface "value(key, default_value)" to get the property of the key, but if the json is null, the call will throw exception like "null cannot use value()", I dont't think it is better...
Why not change it to be used like:

nlohmann::json json /* = ... , from others*/;

// json may be null, or an object

std::string name = json.value("name", ""); // I want  no exception thrown, the name must be some string value or empty string

// and when I use operator[](key) 
void function(const nlohmann::json& args) {
    auto infomation = args["info"];
    if(infomation.is_null()) {
        // some work if it is null, maybe I will use default information 
    }

    if(information.is_object()) {
       // some work if it is an object, maybe I will use default value for some keys in the information object
    }
}

But after I upgraded it to the newest version several days ago, more exception is thrown, and more assertions make the old programs crash... T_T

Why make the change?

Metadata

Metadata

Assignees

No one assigned

    Labels

    solution: invalidthe issue is not related to the library

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions