Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

fix: handle extra closing braces in AI-generated JSON

Wheels Wu78e49c8cb45b
diff --git a/pkg/utils/json_parser.go b/pkg/utils/json_parser.go
index fa09dd1..500ae85 100644
--- a/pkg/utils/json_parser.go
+++ b/pkg/utils/json_parser.go
@@ -123,12 +123,42 @@ func attemptJSONRepair(jsonStr string) string {
openBrackets := strings.Count(trimmed, "[")
closeBrackets := strings.Count(trimmed, "]")
- // 4. 补全未闭合的数组
+ // 4. 处理多余的闭合括号(从末尾移除)
+ // 这是 AI 生成 JSON 时常见的问题
+ for closeBrackets > openBrackets && len(trimmed) > 0 {
+ // 从末尾向前查找多余的 ]
+ lastIdx := strings.LastIndex(trimmed, "]")
+ if lastIdx >= 0 {
+ trimmed = trimmed[:lastIdx] + trimmed[lastIdx+1:]
+ closeBrackets--
+ } else {
+ break
+ }
+ }
+
+ for closeBraces > openBraces && len(trimmed) > 0 {
+ // 从末尾向前查找多余的 }
+ lastIdx := strings.LastIndex(trimmed, "}")
+ if lastIdx >= 0 {
+ trimmed = trimmed[:lastIdx] + trimmed[lastIdx+1:]
+ closeBraces--
+ } else {
+ break
+ }
+ }
+
+ // 重新统计括号(因为可能已修改)
+ openBraces = strings.Count(trimmed, "{")
+ closeBraces = strings.Count(trimmed, "}")
+ openBrackets = strings.Count(trimmed, "[")
+ closeBrackets = strings.Count(trimmed, "]")
+
+ // 5. 补全未闭合的数组
for i := 0; i < openBrackets-closeBrackets; i++ {
trimmed += "]"
}
- // 5. 补全未闭合的对象
+ // 6. 补全未闭合的对象
for i := 0; i < openBraces-closeBraces; i++ {
trimmed += "}"
}
diff --git a/pkg/utils/json_parser_test.go b/pkg/utils/json_parser_test.go
new file mode 100644
index 0000000..cfc0026
--- /dev/null
+++ b/pkg/utils/json_parser_test.go
@@ -0,0 +1,119 @@
+package utils
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+// TestAttemptJSONRepairExcessBraces tests fixing JSON with excess closing braces
+// This is the fix for issue #28: AI sometimes returns JSON with extra closing braces
+func TestAttemptJSONRepairExcessBraces(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ wantErr bool
+ }{
+ {
+ name: "normal JSON",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}]}`,
+ wantErr: false,
+ },
+ {
+ name: "extra closing brace - issue #28 case",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}]}}`,
+ wantErr: false,
+ },
+ {
+ name: "extra closing bracket",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}]]}`,
+ wantErr: false,
+ },
+ {
+ name: "multiple extra closing braces",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}]}}}`,
+ wantErr: false,
+ },
+ {
+ name: "missing closing brace",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}]`,
+ wantErr: false,
+ },
+ {
+ name: "missing closing bracket",
+ input: `{"backgrounds": [{"location": "test", "prompt": "hello"}`,
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var result struct {
+ Backgrounds []struct {
+ Location string `json:"location"`
+ Prompt string `json:"prompt"`
+ } `json:"backgrounds"`
+ }
+
+ err := SafeParseAIJSON(tt.input, &result)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SafeParseAIJSON() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+
+ if !tt.wantErr {
+ // Verify the parsed result
+ if len(result.Backgrounds) != 1 {
+ t.Errorf("Expected 1 background, got %d", len(result.Backgrounds))
+ return
+ }
+ if result.Backgrounds[0].Location != "test" {
+ t.Errorf("Expected location 'test', got '%s'", result.Backgrounds[0].Location)
+ }
+ if result.Backgrounds[0].Prompt != "hello" {
+ t.Errorf("Expected prompt 'hello', got '%s'", result.Backgrounds[0].Prompt)
+ }
+ }
+ })
+ }
+}
+
+// TestAttemptJSONRepairFunction tests the attemptJSONRepair function directly
+func TestAttemptJSONRepairFunction(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ valid bool
+ }{
+ {
+ name: "fix extra closing brace",
+ input: `{"key": "value"}}`,
+ valid: true,
+ },
+ {
+ name: "fix extra closing bracket",
+ input: `["item1", "item2"]]`,
+ valid: true,
+ },
+ {
+ name: "fix missing closing brace",
+ input: `{"key": "value"`,
+ valid: true,
+ },
+ {
+ name: "fix missing closing bracket",
+ input: `["item1", "item2"`,
+ valid: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ repaired := attemptJSONRepair(tt.input)
+ var js json.RawMessage
+ err := json.Unmarshal([]byte(repaired), &js)
+ if tt.valid && err != nil {
+ t.Errorf("attemptJSONRepair() failed to produce valid JSON: %v\nInput: %s\nOutput: %s", err, tt.input, repaired)
+ }
+ })
+ }
+}