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

How to detect parse failure? #715

Closed
davechurchill opened this issue Aug 28, 2017 · 8 comments
Closed

How to detect parse failure? #715

davechurchill opened this issue Aug 28, 2017 · 8 comments

Comments

@davechurchill
Copy link

Apologies for the seemingly simple question, but there is no example for detecting a parse failure on the readme. Maybe one could be added, or a simple explanation of how to detect a parse failure could be given?

@davechurchill
Copy link
Author

@nlohmann I see you saw this and added it to documentation, in the mean time while you work on it could you let me know how? I need it for a project :)

@nlohmann
Copy link
Owner

Parse errors are indicated by exceptions. In the 2.x.x series, the exception type is std::invalid_argument, in 3.x.x (develop branch), the exception type is json::parse_error. See https://github.com/nlohmann/json/blob/develop/doc/examples/parse_error.cpp for an example of the latter.

@davechurchill
Copy link
Author

Thank you for the quick response. Might you consider adding a simple boolean to the json object indicating whether or not there was a parse error? Sometimes it is quite inconvenient to rely on exceptions for some things. Here's a sample use-case:

std::ifstream in(filename)
json j;
in >> j;

if (j.parseError()) { print error message }

@gregmarr
Copy link
Contributor

What is inconvenient about this?

std::ifstream in(filename)
json j;

try {
    in >> j;
} catch(json::parse_error) {
    print error message;
}

@davechurchill
Copy link
Author

davechurchill commented Aug 30, 2017

Nothing is inconvenient about the code itself, apologies for implying that. It is inconvenient in the case where I am working with a codebase that has exceptions disabled :(

I completely understand if the feature request is not doable, just thought it wouldn't hurt to ask :)

@gregmarr
Copy link
Contributor

Oh, that's a different case altogether. #582

std::ifstream in(filename)
json j = json::parse(in, nullptr, false);
if (j.is_discarded()) { print error message }

@davechurchill
Copy link
Author

That's exactly what I'm looking for, thank you!

@naimac
Copy link

naimac commented May 7, 2019

it'll be interesting for newbies like me, to remind that for parsing a jsonFile from the program's argument (linux) we have to do like so :

[linux] ./a.out "cat myFile.json"
[main.cpp] std::string myVar(argv[1])

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

4 participants