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

trying to log message for missing keyword, difference between ["foo"] and at("foo") #1593

Closed
cwreynolds opened this issue May 1, 2019 · 2 comments

Comments

@cwreynolds
Copy link

I want to print a helpful message when a required keyword is missing from a json file. I mimicked the example code given here to print a message about a caught exception. Instead of printing “key 'foo' not found” it continued to print the less helpful “type must be number, but is null”. I eventually realized that the difference was not related to handling the exception—the default handler was fine—but it came down to how I wrote the keyword lookup. This produces “type must be number, but is null”:

float foo = properties["foo"];

While this produces what I wanted, “key ‘foo’ not found”:

float foo = properties.at("foo");

Is this an intentional/expected difference between [] and at()? And is the solution to my desire for more specific “keyword not found” error messages simply to use at() instead of []? Or is something more subtle going on?

(I’m using version 3.6.1)

@gregmarr
Copy link
Contributor

gregmarr commented May 1, 2019

Yes, properties["foo"] creates a new null entry if the entry isn't found and properties is not const. If it is const, then it asserts (I think). If you aren't sure if it's there, you need to use find() first to check, or at() with exception handling.

@cwreynolds
Copy link
Author

Thanks @gregmarr for the explanation. Performance of json reading is not a key issue in my application, it only happens at initialization. So I will replace [] with at() on nlohmann::json objects in order to get better error messages “for free.”

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

No branches or pull requests

2 participants