diff --git a/internal/magic/magic_test.go b/internal/magic/magic_test.go new file mode 100644 index 00000000..f89aff84 --- /dev/null +++ b/internal/magic/magic_test.go @@ -0,0 +1,20 @@ +package magic + +import "testing" + +var magicTests = []struct { + raw string + limit uint32 + res bool + detector Detector +}{ + {`["an incomplete JSON array`, 0, false, JSON}, +} + +func TestMagic(t *testing.T) { + for i, tt := range magicTests { + if got := tt.detector([]byte(tt.raw), tt.limit); got != tt.res { + t.Errorf("Detector %d error: expected: %t; got: %t", i, tt.res, got) + } + } +} diff --git a/internal/magic/text.go b/internal/magic/text.go index 026c6aad..40bfb190 100644 --- a/internal/magic/text.go +++ b/internal/magic/text.go @@ -155,12 +155,14 @@ func Php(raw []byte, limit uint32) bool { // JSON matches a JavaScript Object Notation file. func JSON(raw []byte, limit uint32) bool { raw = trimLWS(raw) - if len(raw) == 0 || (raw[0] != '[' && raw[0] != '{') { + // #175 A single JSON string, number or bool is not considered JSON. + // JSON objects and arrays are reported as JSON. + if len(raw) < 2 || (raw[0] != '[' && raw[0] != '{') { return false } parsed, err := json.Scan(raw) // If the full file content was provided, check there is no error. - if len(raw) < int(limit) { + if limit == 0 || len(raw) < int(limit) { return err == nil }