Skip to content

Commit

Permalink
fix: fix scraping JSON with escaped backslashes towards end of strings (
Browse files Browse the repository at this point in the history
#862)

* fix escaped backslashes towards end of string & add test

* Update lib/utils.js

Co-authored-by: fent <fentbox@gmail.com>

* linting

Co-authored-by: fent <fentbox@gmail.com>
  • Loading branch information
TimeForANinja and fent committed Jan 20, 2021
1 parent 15e7fac commit 540d50b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/utils.js
Expand Up @@ -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) {
Expand Down
6 changes: 6 additions & 0 deletions test/utils-test.js
Expand Up @@ -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'),
Expand Down

0 comments on commit 540d50b

Please sign in to comment.