Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json class should have a get_or member function #1823

Closed
NotAPenguin0 opened this issue Nov 1, 2019 · 2 comments
Closed

json class should have a get_or member function #1823

NotAPenguin0 opened this issue Nov 1, 2019 · 2 comments
Labels
kind: enhancement/improvement solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@NotAPenguin0
Copy link

NotAPenguin0 commented Nov 1, 2019

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

@nlohmann
Copy link
Owner

nlohmann commented Nov 1, 2019

This function exists and it is called value().

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Nov 1, 2019
@NotAPenguin0
Copy link
Author

Didn't know about that one, thanks for the reply!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: enhancement/improvement solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

2 participants