Skip to content

Recover from Parsing Errors and Continue JSON Processing With Ondemand Parser #2347

Closed

Description

@Cirnoo

Request: Recover from Parsing Errors and Continue JSON Processing

Description

Hi~, I am using simdjson::ondemand::parser to parse JSON data, but sometimes my JSON objects may contain malformed elements (e.g., trailing commas). While I understand that such structures are invalid according to strict JSON specifications, I would like to have an option to skip or recover from errors rather than having the entire parsing process fail.

Some JSON libraries, such as yyjson, provide support for trailing commas or other minor syntax relaxations. My main concern is not just about trailing commas but about having a way to recover from an error and continue parsing the rest of the JSON object.

Example Code

simdjson::ondemand::parser parser;
simdjson::ondemand::document doc;
std::string data = R"({
    "errorObj": {
        "key" : "value", // Trailing comma, invalid JSON
    },
    "extData": {
        "key2" : "some data in here"
    }
})";

auto error = parser.iterate(data).get(doc);
auto root = doc.get_object().value();

// If I try to access `errorObj` first, my code crashes.
// However, if I avoid accessing `errorObj`, the code runs fine.

// try {
//     auto errorObj = root["errorObj"].take_value();
//     auto size = errorObj.count_fields().take_value();
//     std::cout << "error object size = " << size << std::endl;
// } catch (const std::exception & e) {
//     std::cout << "error: " << e.what() << std::endl;
//     // Is there a way to reset the error and continue parsing the rest of the JSON?
// }

try {
    auto extData = root["extData"].take_value();
    auto size = extData.count_fields();
    std::cout << "extData object size = " << size;
} catch (const std::exception & e) {
    std::cout << "error: " << e.what() << std::endl;
}

I hope that the ondemand parser could incorporate some level of error tolerance and recovery capabilities to support more complex and customized scenarios for users.

Thank you for considering this feature request. Your work on simdjson is greatly appreciated!

Activity

  1. lemire commented on Mar 12, 2025

    @lemire
    Member

    @Cirnoo The simdjson library validates what you parse, so it will happily accept bad JSON as long as it does not need to access the bad JSON...

    #include "simdjson.h"
    #include <iostream>
    
    using namespace simdjson;
    
    int main() {
      simdjson::padded_string data = R"({
        "errorObj": {
            "key" : "value", // Trailing comma, invalid JSON
        },
        "extData": {
            "key2" : "some data in here"
        }
    })"_padded;
    
      simdjson::ondemand::parser parser;
      simdjson::ondemand::document doc = parser.iterate(data);
      auto root = doc.get_object();
      std::string_view v = root["errorObj"]["key"].get_string();
      std::cout << v << std::endl;
      v = root["extData"]["key2"].get_string();
      std::cout << v << std::endl;
      /**
       * Prints:
       * value
       * some data in here 
       */
      return EXIT_SUCCESS;
    }

    In your example, you want to access all fields (count_fields()) which triggers an error, as expected... because to count the fields, you need to access all of them...

    I hope that the ondemand parser could incorporate some level of error tolerance and recovery capabilities...

    That's not unreasonable, but it is also likely tricky to get right.

    It is easy (even automatic) to recover from atomic values that are broken (strings, numbers), but structures (anything to do with brackets and commas) is tricky.

    The problem is that once the JSON structure is broken, it is very difficult to reason about what goes where. In the example with ""errorObj", are there one or two fields?

    In any case, if you need this feature and are willing to work on it, we welcome pull requests ! We could add this as an optional (experimental) feature.

  2. Cirnoo commented on Mar 12, 2025

    @Cirnoo
    Author

    When I convert JSON to STL containers such as map or vector, it often requires iterating over all JSON members. If there is dirty data and it is not returned, this can cause the program to crash (as seen in my code above)

    but it is also likely tricky to get right.

    Yes, I've realized that it's not a simple task, and I might try to implement this feature. Thanks again.

  3. lemire commented on Mar 12, 2025

    @lemire
    Member

    this can cause the program to crash

    It should not crash... not if you are handling the errors or catching the exceptions.

  4. Cirnoo commented on Mar 13, 2025

    @Cirnoo
    Author

    It should not crash... not if you are handling the errors or catching the exceptions.

    Sorry, maybe my previous description was not clear. My example code indeed crashes. Here are the details of my testing environment:

    Operating System: macOS
    Architecture: ARM64
    Compiler: Apple Clang version 16.0.0

    I observed that when iterating over the internal elements of errorObj , and an exception triggers function json_iterator::abandon be called, causing the parser to be set to null. Here is the call stack (I'm using simdjson version 3.12.2):

    simdjson::arm64::ondemand::json_iterator::abandon simdjson.h:39787
    simdjson::arm64::ondemand::value_iterator::abandon simdjson.h:42335
    simdjson::arm64::ondemand::object_iterator::operator* simdjson.h:40629
    simdjson::simdjson_result::operator* simdjson.h:40716
    simdjson::arm64::ondemand::object::count_fields() & simdjson.h:40499
    simdjson::simdjson_result<simdjson::arm64::ondemand::object>::count_fields() & simdjson.h:40588
    simdjson::arm64::ondemand::value::count_fields() & simdjson.h:37590
    main main.cpp:25 (starting the iteration over the internal elements of errorObj)
    

    The abandon function:

    simdjson_inline void json_iterator::abandon() noexcept {
      parser = nullptr;
      _depth = 0;
    }

    As a result, when the parser is set to null and I try to access root["extData"], it leads to a null pointer exception:

    EXC_BAD_ACCESS (code=1, address=0x8)
    callstack:
    std::unique_ptr::operator->[abi:ne180100] const unique_ptr.h:246
    simdjson::arm64::ondemand::json_iterator::end_position const simdjson.h:39754
    simdjson::arm64::ondemand::json_iterator::skip_child simdjson.h:39683
    simdjson::arm64::ondemand::value_iterator::skip_child simdjson.h:42303
    simdjson::arm64::ondemand::value_iterator::find_field_unordered_raw simdjson.h:41767
    simdjson::arm64::ondemand::object::find_field_unordered(std::__1::basic_string_view<char, std::__1::char_traits<char>>) & simdjson.h:40341
    simdjson::arm64::ondemand::object::operator[](std::__1::basic_string_view<char, std::__1::char_traits<char>>) & simdjson.h:40358
    main main.cpp:33 (access the root["extData"])
    

    Complete code:

    simdjson::ondemand::parser parser;
    simdjson::ondemand::document doc;
    std::string data = R"({
      "errorObj": {
        "key" : "value", // Incorrect JSON structure
      },
      "extData": {
        "key2" : "some data in here"
      }
    })";
    
    auto error = parser.iterate(data).get(doc);
    auto root = doc.get_object().value();
    
    try {
        auto errorObj = root["errorObj"].take_value();
        auto size = errorObj.count_fields().take_value();
        std::cout << "error object size = " << size << std::endl;
    } catch (const std::exception & e) {
        std::cout << "error: " << e.what() << std::endl;
    
    }
    
    try {
        auto extData = root["extData"].take_value();    // crash at hear
        auto size = extData.count_fields();
        std::cout << "extData object size = " << size;
    } catch (const std::exception & e) {
        std::cout << "error: " << e.what() << std::endl;
    }
    
  5. lemire commented on Mar 13, 2025

    @lemire
    Member

    Sorry, maybe my previous description was not clear. My example code indeed crashes

    Once you have encountered an error in the JSON content, you can catch the exception and your code is going to be fine.

    However, you cannot ignore the error and continue as if nothing happened. The error is deliberately fatal.

    By analogy, consider the following...

    char * pointer;
    
    try {
      pointer = new char [10]; 
    } catch(std::bad_alloc & e) {
     // I am deliberately ignoring the error.
    }
    
    // Because I have deliberately ignored the fatal error, I should not access 'pointer'
    
    pointer[0] = 1;
    

    Here is proper code (by analogy):

    char * pointer;
    
    try {
      pointer = new char [10]; 
      pointer[0] = 1; // when the exception is thrown by the previous line, I do not get here
    } catch(std::bad_alloc & e) {
     // I am deliberately ignoring the error.
    }
    

    When accessing an atomic value (string, number), it is fine to recover from the error, but not when you have encountered a broken structure, then the error is fatal. We cannot continue as there is no safe way to parse broken JSON content (it is fine to skip over it, however).

  6. lemire commented on Sep 22, 2026

    @lemire
    Member

    To summarize the discussion above: On Demand only validates what you access, so malformed content you skip doesn't cause an error. A structural error that you do run into (like a trailing comma inside an object you're iterating) is deliberately fatal, because the iterator can't safely resume inside broken structure. After such an error, stop using that document. Errors on atomic values (a string, a number) are recoverable. This is intended behavior, and we don't plan to add lenient or recovering parsing. Closing.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions