| import re | |
| import pathlib | |
| import shutil | |
| import argparse | |
| def escape_backslashes_in_questions(text: str) -> str: | |
| # 匹配 "question": "..." | |
| json_string = r'"(?:\\.|[^"\\])*"' | |
| pattern = re.compile(rf'("question"\s*:\s*)({json_string})') | |
| def replacer(m): | |
| prefix, raw = m.groups() | |
| # 去掉外层引号 | |
| inner = raw[1:-1] | |
| # 把单反斜杠替换成双反斜杠 | |
| inner_fixed = inner.replace("\\", "\\\\") | |
| return f'{prefix}"{inner_fixed}"' | |
| return pattern.sub(replacer, text) | |
| def process_file(p: pathlib.Path): | |
| original = p.read_text(encoding="utf-8") | |
| fixed = escape_backslashes_in_questions(original) | |
| if fixed != original: | |
| shutil.copyfile(p, p.with_suffix(p.suffix + ".bak")) | |
| p.write_text(fixed, encoding="utf-8") | |
| print(f"[UPDATED] {p}") | |
| else: | |
| print(f"[SKIP ] {p}") | |
| def main(): | |
| ap = argparse.ArgumentParser(description="Fix backslashes in 'question' fields of JSON files") | |
| ap.add_argument("folder", type=str, help="Directory containing .json files") | |
| args = ap.parse_args() | |
| root = pathlib.Path(args.folder) | |
| if not root.is_dir(): | |
| print(f"[ERROR] {args.folder} is not a valid directory") | |
| return | |
| for p in root.glob("*.json"): | |
| process_file(p) | |
| if __name__ == "__main__": | |
| main() | |