File size: 1,574 Bytes
df50c21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import json
import re
import os

def fix_json_string(json_str):
    # Replace single backslashes with double backslashes
    # but only when they're not already properly escaped
    return re.sub(r'(?<!\\)\\(?!["\\])', r'\\\\', json_str)

def check_and_fix_jsonl_file(input_file_path):
    # Create output filename by adding '_fixed' before the extension
    base, ext = os.path.splitext(input_file_path)
    output_file_path = f"{base}_fixed{ext}"
    
    fixed_lines = []
    has_errors = False
    
    with open(input_file_path, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            try:
                # Try to fix the JSON string before parsing
                fixed_line = fix_json_string(line)
                # Verify the fix worked by parsing
                json.loads(fixed_line)
                fixed_lines.append(fixed_line)
            except json.JSONDecodeError as e:
                has_errors = True
                print(f"Error on line {line_num}: {str(e)}")
                print(f"Problematic line content: {line.strip()}")
    
    if has_errors:
        print("\nSome lines had errors and may not be properly fixed.")
    
    # Write the fixed lines to the new file
    with open(output_file_path, 'w', encoding='utf-8') as f:
        f.writelines(fixed_lines)
    
    print(f"\nFixed JSONL file saved to: {output_file_path}")

if __name__ == "__main__":
    file_path = "data/test.jsonl"
    print(f"Checking and fixing file: {file_path}")
    check_and_fix_jsonl_file(file_path)
    print("Process complete")