fix-subsection-parser.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const fs = require('fs');
  2. const file = 'src/modules/book-generator/langgraph-generator.ts';
  3. let content = fs.readFileSync(file, 'utf8');
  4. // 修复1:添加双重转义处理
  5. const fix1 = ` // 调试:打印前80个字符
  6. console.log('[SubsectionParser] 原始前80字符:', JSON.stringify(cleanedStr.substring(0, 80)));
  7. // 处理双重转义:将 \\n 转换为 \n,\\t 转换为 \t 等
  8. cleanedStr = cleanedStr.replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t').replace(/\\\\r/g, '\\r');
  9. // 清理 JSON 字符串中的非法控制字符`;
  10. content = content.replace(
  11. ` // 调试:打印前80个字符
  12. console.log('[SubsectionParser] 原始前80字符:', JSON.stringify(cleanedStr.substring(0, 80)));
  13. // 清理 JSON 字符串中的非法控制字符`,
  14. fix1
  15. );
  16. // 修复2:添加正则提取容错
  17. const fix2 = ` } catch (parseErr) {
  18. // 尝试使用正则提取 subsections 数组
  19. console.log('[SubsectionParser] 首次解析失败,尝试正则提取');
  20. const subsectionsMatch = jsonCandidate.match(/"subsections"\\s*:\\s*(\\[[\\s\\S]*\\])/);
  21. if (subsectionsMatch) {
  22. try {
  23. const subsectionsJson = subsectionsMatch[1];
  24. data = { subsections: JSON.parse(subsectionsJson) };
  25. } catch (e) {
  26. console.error('[SubsectionParser] 正则提取后解析仍失败:', e);
  27. return null;
  28. }
  29. } else {
  30. console.error('[SubsectionParser] JSON 解析失败:', parseErr);
  31. return null;
  32. }
  33. }`;
  34. content = content.replace(
  35. ` } catch (parseErr) {
  36. console.error('[SubsectionParser] JSON 解析失败:', parseErr);
  37. return null;
  38. }`,
  39. fix2
  40. );
  41. fs.writeFileSync(file, content, 'utf8');
  42. console.log('✅ parseSubsections 修复完成');