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

Is there a way to get an element from a JSON without throwing an exception on failure? #1182

Closed
014972304505347 opened this issue Aug 1, 2018 · 3 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@014972304505347
Copy link

014972304505347 commented Aug 1, 2018

For example, say j is an nlohmann::json object. I want to try to get a member called "raw" using the following code, but without throwing an exception if it fails -- exceptions seem to be a time bottleneck in my application.

        p.raw = j.at("raw").get<int>();

Is it possible?

@014972304505347 014972304505347 changed the title Is there a way to do try to get an element from a JSON without throwing an exception on failure? Is there a way to get an element from a JSON without throwing an exception on failure? Aug 1, 2018
@gregmarr
Copy link
Contributor

gregmarr commented Aug 1, 2018

It depends on whether you want to know if it's there or not, or if you want to get a default value if it's not. If you want to know, use find() first. If you don't care, use value() which takes a default value.

@nlohmann
Copy link
Owner

nlohmann commented Aug 1, 2018

I doubt that exceptions are really a time bottleneck, but you could use:

if (j.find("raw") != j.end() and j.is_number_integer())
{
  p.raw = j["raw"];
}

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Aug 1, 2018
@014972304505347
Copy link
Author

Changing the code to this:

      p.raw = j.value("raw",0);

seems to have fixed the problem. Before, the code was taking around 12milliseconds to run when the element wasn't available. Now it takes about 6 microseconds even if the element isn't available. Thanks!

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

No branches or pull requests

3 participants