Skip to content

Commit

Permalink
Replace JSON11-produced hex escape codes with unicode escape codes
Browse files Browse the repository at this point in the history
JSON11.stringify produces JSON5 documents with hex escape codes (`\x1b`),
which aren't standard JSON and cause `JSON.parse` to error.
When using JSON11, replace all `\xXX` escape codes with the JSON-compatible
equivalent Unicode escape codes (`\u00XX`).

Fixes #7367.
  • Loading branch information
wjordan committed Sep 26, 2024
1 parent 1db585d commit ac0eae9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/osd-std/src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,4 +173,10 @@ describe('json', () => {

expect(stringify(input, replacer, 4)).toMatchSnapshot();
});

it('can handle BigInt values and ANSI escape sequences', () => {
const input = {message: "hello \u001b[38;7;2mworld\u001b[0m", value: BigInt(Number.MAX_SAFE_INTEGER) * 2n};
const result = parse(stringify(input));
expect(result).toEqual(input);
})
});
3 changes: 2 additions & 1 deletion packages/osd-std/src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/

import JSON11 from 'json11';
const hexEscapeRegex = /\\x([0-9A-Fa-f]{2})/g;

export const stringify = (
obj: any,
Expand Down Expand Up @@ -52,7 +53,7 @@ export const stringify = (
quote: '"',
quoteNames: true,
});
if (temp) text = temp;
if (temp) text = temp.replace(hexEscapeRegex, (_, c) => `\\u00${c}`);
}

return text;
Expand Down

0 comments on commit ac0eae9

Please sign in to comment.