json_repair/
repair_json_parallel.rs

1crate::ix!();
2
3pub fn repair_json_string_parallel(input: &str) -> Result<Value, JsonRepairError> {
4    if input.trim().is_empty() {
5        return Ok(serde_json::json!({}));
6    }
7
8    // Attempt to parse the input as-is.
9    if let Ok(mut value) = json5::from_str(&input) {
10        remove_control_characters_in_value(&mut value);
11        return Ok(value);
12    }
13
14    if let Ok(repaired) = attempt_repair_json_string(input) {
15        return Ok(repaired);
16    }
17
18    // Define a list of repair functions.
19    let repair_functions: Vec<fn(&str) -> Result<String, JsonRepairError>> = vec![
20        repair_json_accidental_single_quote_instead_of_double_quote,
21        repair_json_comma_behavior,
22        repair_json_truncated_boolean_behavior,
23        repair_json_mismatched_brackets,
24        repair_json_control_characters,
25        repair_json_missing_commas_in_list,
26        repair_json_remove_duplicate_quotes,
27        repair_json_close_unexpected_eof,
28        repair_json_add_missing_quotes,
29        repair_json_handle_eof_between_lists,
30        repair_json_fix_mismatched_quotes,
31        repair_json_close_unexpected_eof_in_array_tag,
32        repair_json_close_unexpected_eof_in_array_item,
33    ];
34
35    // First round: Try each repair independently.
36    for repair_fn in &repair_functions {
37        let repaired_input = match repair_fn(input) {
38            Ok(output) => output,
39            Err(_) => continue, // Skip if repair function fails.
40        };
41
42        if let Ok(repaired) = attempt_repair_json_string(&repaired_input) {
43            return Ok(repaired);
44        }
45    }
46
47    // Optional: Second round with combinations of repairs.
48    // This can be implemented if needed.
49
50    // If all repairs fail, return an error.
51    Err(JsonRepairError::AllAttemptedRepairsFailed)
52}
53