I'm need to read some *.json file, but this file can have invalid json format. How to check for right json format before or while parsing?
You can now pass a boolean allow_exceptions to the parse functions. If it is false, no exceptions are thrown in case of a parse error. Instead, parsing is stopped at the first error and a JSON value of type "discarded" (check with is_discarded()) is returned.
FYI: It is now possible to call static bool accept(i) with any type i from which an input adapter can be constructed. Basically, i can have the same types as static basic_json parse(i). This function returns true iff the input contains a valid serialized JSON value. No exceptions are thrown in case of an error.
With b27d2ad I added a family static bool accept() functions that accept the same parameters as the parse() family (without the callback parameter) and return true if and only if the provided input is a valid JSON text. In case a parse error occurs, no exception is thrown.
How to use this function?
Use accept instead of parse and take the bool it returns.
I have encountered the same issue, I could not catch anything that parse might throw. However I dug myself into the code to see the inheritence of the exception classes, and as far as I could get none of these exception declaration seemed worked, and passed through:
```.cpp
using Json = nlohmann::json;
//...
try {
Json::parse(data);
}
catch (const Json::parse_error &e) { //...
}
catch (const Json::exception &e) { //...
}
catch (const std::exception &e) { //...
}
```
I don't want to open another issue, due already there's a similar one, but are there any method to get at least an error message of the reason of the failure? It is mandatory for me, because the JSON document comes directly form a user input, and have to prompt it.
@caiwan Which version are you using? In https://nlohmann.github.io/json/classnlohmann_1_1basic__json_af1efc2468e6022be6e35fc2944cabe4d.html#af1efc2468e6022be6e35fc2944cabe4d is an example how to catch parse error exceptions.
I've tried it with no const qualifiers, and still no luck.
I use the lastest stable v3.1.2 with Visual Studio 2015 (Version 14.0.25431.01 Update 3), within a Google Test testcase.
If I'll have a little extra time, I'd hack together a PoC project to reproduce the issue.
I'd be really interested, because we are using MSVC 2015 in our CI chain since we introduced the new exceptions in 3.0.0 and never heard of any issues.
Most helpful comment
Use
acceptinstead ofparseand take theboolit returns.