辅助函数
(content string)
| 445 | // 辅助函数 |
| 446 | |
| 447 | func extractJSON(content string) string { |
| 448 | // 尝试提取 JSON(可能在代码块中或包含额外文本) |
| 449 | |
| 450 | // 首先尝试找到 JSON 对象的开始和结束 |
| 451 | start := strings.Index(content, "{") |
| 452 | if start == -1 { |
| 453 | return content |
| 454 | } |
| 455 | |
| 456 | // 使用简单的括号匹配来找到对应的结束括号 |
| 457 | depth := 0 |
| 458 | inString := false |
| 459 | escaped := false |
| 460 | |
| 461 | for i := start; i < len(content); i++ { |
| 462 | ch := content[i] |
| 463 | |
| 464 | // 处理转义字符 |
| 465 | if escaped { |
| 466 | escaped = false |
| 467 | continue |
| 468 | } |
| 469 | |
| 470 | if ch == '\\' { |
| 471 | escaped = true |
| 472 | continue |
| 473 | } |
| 474 | |
| 475 | // 处理字符串 |
| 476 | if ch == '"' { |
| 477 | inString = !inString |
| 478 | continue |
| 479 | } |
| 480 | |
| 481 | // 只在非字符串内部计数括号 |
| 482 | if !inString { |
| 483 | switch ch { |
| 484 | case '{': |
| 485 | depth++ |
| 486 | case '}': |
| 487 | depth-- |
| 488 | if depth == 0 { |
| 489 | // 找到匹配的结束括号 |
| 490 | return content[start : i+1] |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | // 如果没有找到匹配的括号,使用原来的简单方法 |
| 497 | end := strings.LastIndex(content, "}") |
| 498 | if end != -1 && end > start { |
| 499 | return content[start : end+1] |
| 500 | } |
| 501 | |
| 502 | return content |
| 503 | } |