Skip to content

Commit

Permalink
Detect quoted strings and unquoted numbers as JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
vgrichina committed Oct 5, 2023
1 parent 50f9fce commit 6d5e6fe
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
3 changes: 3 additions & 0 deletions test/is-json.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(' {} '))));
Expand Down
2 changes: 1 addition & 1 deletion utils/is-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 6d5e6fe

Please sign in to comment.