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) + }) +})