Skip to content

json class should have a get_or member function #1823

Description

@NotAPenguin0

I found the need to write a free function

template<typename T>
void json_get_or(nlohmann::json const& j,
                 std::string_view key,
                 T& dest,
                 T const& default_val = T{}) {
    if (auto json_it = j.find(key); json_it != j.end()) {
        dest = (*json_it).get<T>();
    } else {
        dest = default_val;
    }
}

This way, I can get a value from a json object, and a default value if they key is not present. It would be great to have this as a member function of json, e.g.
int x = json.get_or<int>("x", 0); // 0 is default value

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions