From 1034107b19b58a29880d229f2ab35066062661a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96zg=C3=BCr=20=C3=96z=C3=A7=C4=B1tak?= Date: Tue, 4 Aug 2020 12:32:45 +0300 Subject: [PATCH] Escape JSON special chars. Fixes #44 --- src/writers/JSONCBWriter.ts | 2 +- src/writers/JSONWriter.ts | 2 +- test/issues/issue-044.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 test/issues/issue-044.test.ts diff --git a/src/writers/JSONCBWriter.ts b/src/writers/JSONCBWriter.ts index b820692f..aa0e0ae5 100644 --- a/src/writers/JSONCBWriter.ts +++ b/src/writers/JSONCBWriter.ts @@ -150,7 +150,7 @@ export class JSONCBWriter extends BaseCBWriter { * Produces a JSON value string delimited with double quotes. */ private _val(val: string): string { - return "\"" + val + "\"" + return JSON.stringify(val) } } diff --git a/src/writers/JSONWriter.ts b/src/writers/JSONWriter.ts index 97f2e530..4250e3f7 100644 --- a/src/writers/JSONWriter.ts +++ b/src/writers/JSONWriter.ts @@ -96,7 +96,7 @@ export class JSONWriter extends BaseWriter { } markup += '}' } else { - markup += '"' + obj + '"' + markup += JSON.stringify(obj) } return markup } diff --git a/test/issues/issue-044.test.ts b/test/issues/issue-044.test.ts new file mode 100644 index 00000000..07c85523 --- /dev/null +++ b/test/issues/issue-044.test.ts @@ -0,0 +1,24 @@ +import $$ from '../TestHelpers' +import { select } from "xpath" + +describe('Replicate issue', () => { + + // https://github.com/oozcitak/xmlbuilder2/issues/44 + test('#44 - Converting XML to JSON does not escape invalid string characters', () => { + const jsonStr = $$.convert('b\nc', { format: 'json' }) + expect(jsonStr).toBe(`{"a":"b\\nc"}`) + + const invalidChars = Array.from(Array(0x20), (_, i) => { + return String.fromCharCode(i); + }).concat('"', '\\') + + const xml = $$.convert( + `${invalidChars.map((c) => `_${c}_`).join('\n')}` + ) + const json = $$.convert(xml, { format: 'json' }) + expect(() => JSON.parse(json)).not.toThrow() + + const obj = $$.convert(xml, { format: 'object' }) + expect(JSON.stringify(obj)).toBe(json) + }) +})