From 540d50b38f4de8bccf79780e02dfa5d5ad4f0e01 Mon Sep 17 00:00:00 2001 From: TimeForANinja Date: Wed, 20 Jan 2021 17:47:08 +0100 Subject: [PATCH] fix: fix scraping JSON with escaped backslashes towards end of strings (#862) * fix escaped backslashes towards end of string & add test * Update lib/utils.js Co-authored-by: fent * linting Co-authored-by: fent --- lib/utils.js | 10 +++++++++- test/utils-test.js | 6 ++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/utils.js b/lib/utils.js index b1cc349a..c1595606 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -72,16 +72,24 @@ exports.cutAfterJSON = mixedJson => { // States if the loop is currently in a string let isString = false; + // States if the current character is treated as escaped or not + let isEscaped = false; + // Current open brackets to be closed let counter = 0; let i; for (i = 0; i < mixedJson.length; i++) { // Toggle the isString boolean when leaving/entering string - if (mixedJson[i] === '"' && mixedJson[i - 1] !== '\\') { + if (mixedJson[i] === '"' && !isEscaped) { isString = !isString; continue; } + + // Toggle the isEscaped boolean for every backslash + // Reset for every regular character + isEscaped = mixedJson[i] === '\\' && !isEscaped; + if (isString) continue; if (mixedJson[i] === open) { diff --git a/test/utils-test.js b/test/utils-test.js index 14b7e6d7..fe2e3e76 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -63,6 +63,12 @@ describe('utils.cutAfterJSON()', () => { '{"a": "\\\\фыва", "b": 1, "c": {"test": 1}}', ); }); + it('Works with \\\\ towards the end of a string', () => { + assert.strictEqual( + utils.cutAfterJSON('{"text": "\\\\"};'), + '{"text": "\\\\"}', + ); + }); it('Works with [ as start', () => { assert.strictEqual( utils.cutAfterJSON('[{"a": 1}, {"b": 2}]abcd'),