Skip to content

Commit 9a5c191

Browse files
bukzorclaude
andcommitted
Fix #160: Anchor IsJSON regex to prevent false positives on CDATA
The IsJSON() function was using an unanchored regex `\s*[{\[]` which would match a `[` character anywhere in the input. This caused XML documents containing CDATA sections like `<![CDATA[text]]>` to be incorrectly detected as JSON. Changed the regex to `^\s*[{\[]` to anchor it to the start of the input string. Now only inputs that actually begin with `{` or `[` (after optional whitespace) will be detected as JSON. Added TestIsJSON with test cases including CDATA to verify the fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent ec5a59a commit 9a5c191

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

cmd/root_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,25 @@ Bye.`,
211211
})
212212
}
213213
}
214+
215+
func TestIsJSON(t *testing.T) {
216+
tests := []struct {
217+
input string
218+
expected bool
219+
}{
220+
{"{}", true},
221+
{"[]", true},
222+
{" {}", true},
223+
{"\t[", true},
224+
{"<root></root>", false},
225+
{"<![CDATA[text]]>", false}, // Bug #160: should not match [ in CDATA
226+
{"plain text", false},
227+
}
228+
229+
for _, tt := range tests {
230+
t.Run(tt.input, func(t *testing.T) {
231+
result := utils.IsJSON(tt.input)
232+
assert.Equal(t, tt.expected, result)
233+
})
234+
}
235+
}

internal/utils/utils.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ func IsHTML(input string) bool {
519519

520520
func IsJSON(input string) bool {
521521
input = strings.ToLower(input)
522-
matched, _ := regexp.MatchString(`\s*[{\[]`, input)
522+
matched, _ := regexp.MatchString(`^\s*[{\[]`, input)
523523
return matched
524524
}
525525

0 commit comments

Comments
 (0)