Skip to content

easier way to get exception reason out of json_sax_dom_callback_parser without exceptions #2024

@esromneb

Description

@esromneb
  • Describe the feature in as much detail as possible.

I am forced to disable exceptions in my project as I am targeting WASM with Emscripten.

I was able to use the code below to parse json from a std::string without using any exceptions. This works great for me however if I do hit a parse error, I would like to know what the error was. Looking at class parser::parse() it uses a json_sax_dom_callback_parser, which inturn calls parse_error(). But there is no way to get the details of what happened from there when allow_exceptions is false. Is it possible to add a callback somewhere that accepts a parse_error or something like that?

  • Include sample usage where appropriate.

This is the function I'm using so far:

using nlohmann::detail::input_buffer_adapter ;
std::optional<nlohmann::json> jsonParseExceptionFree(const std::string& str) {
    const char* first = str.c_str();
    auto len = str.size();

    // The resulting json object
    nlohmann::json j;

    // some stuff I don't understand
    auto ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
    nlohmann::detail::parser<nlohmann::basic_json<>>(ia, nullptr, false).parse(false, j);

    if( j.is_discarded() ) {
        // parse error
        return {};
    } else {
        // parsed correctly
        return j;
    }
}

Thanks for the help, I really love this library but the internals are more complicated than I understand.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions