Skip to content

Commit

Permalink
Escape JSON special chars. Fixes #44
Browse files Browse the repository at this point in the history
  • Loading branch information
oozcitak committed Aug 4, 2020
1 parent 6dddfb1 commit 1034107
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/writers/JSONCBWriter.ts
Expand Up @@ -150,7 +150,7 @@ export class JSONCBWriter extends BaseCBWriter<JSONCBWriterOptions> {
* Produces a JSON value string delimited with double quotes.
*/
private _val(val: string): string {
return "\"" + val + "\""
return JSON.stringify(val)
}

}
2 changes: 1 addition & 1 deletion src/writers/JSONWriter.ts
Expand Up @@ -96,7 +96,7 @@ export class JSONWriter extends BaseWriter<JSONWriterOptions, string> {
}
markup += '}'
} else {
markup += '"' + obj + '"'
markup += JSON.stringify(obj)
}
return markup
}
Expand Down
24 changes: 24 additions & 0 deletions 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('<a>b\nc</a>', { format: 'json' })
expect(jsonStr).toBe(`{"a":"b\\nc"}`)

const invalidChars = Array.from(Array(0x20), (_, i) => {
return String.fromCharCode(i);
}).concat('"', '\\')

const xml = $$.convert(
`<a>${invalidChars.map((c) => `<b>_${c}_</b>`).join('\n')}</a>`
)
const json = $$.convert(xml, { format: 'json' })
expect(() => JSON.parse(json)).not.toThrow()

const obj = $$.convert(xml, { format: 'object' })
expect(JSON.stringify(obj)).toBe(json)
})
})

0 comments on commit 1034107

Please sign in to comment.