From 6d5e6fe711cda884b674c7f519a1bf4386ea9a01 Mon Sep 17 00:00:00 2001 From: Vladimir Grichina Date: Thu, 5 Oct 2023 13:35:20 -0700 Subject: [PATCH] Detect quoted strings and unquoted numbers as JSON --- test/is-json.test.js | 3 +++ utils/is-json.js | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/test/is-json.test.js b/test/is-json.test.js index 4d34e93..1e8b131 100644 --- a/test/is-json.test.js +++ b/test/is-json.test.js @@ -6,6 +6,9 @@ const isJSON = require('../utils/is-json'); test('empty is not JSON', async t => t.false(isJSON(Buffer.from([])))); test('binary is not JSON', async t => t.false(isJSON(Buffer.from([1, 2, 3])))); +test('quoted string is JSON', async t => t.true(isJSON(Buffer.from('"Hello, World!"')))); +test('quoted integer is JSON', async t => t.true(isJSON(Buffer.from('"12345"')))); +test('arbitrary integer is JSON', async t => t.true(isJSON(Buffer.from('12345')))); test('arbitrary string is not JSON', async t => t.false(isJSON(Buffer.from('Hello, World!')))); test('should detect JSON object', async t => t.true(isJSON(Buffer.from('{}')))); test('should detect JSON object with trailing whitespace', async t => t.true(isJSON(Buffer.from(' {} ')))); diff --git a/utils/is-json.js b/utils/is-json.js index 516495d..fa4dc7f 100644 --- a/utils/is-json.js +++ b/utils/is-json.js @@ -2,7 +2,7 @@ function isJSON(buffer) { try { const MAX_WHITESPACE = 1000; const startSlice = buffer.slice(0, MAX_WHITESPACE + 1).toString('utf8').trim(); - if (startSlice.startsWith('{') || startSlice.startsWith('[')) { + if (/^\s*[\[\{"\d]/.test(startSlice)) { JSON.parse(buffer.toString('utf8')); return true; }