diff --git a/index.js b/index.js index cf1c4c72..b4400d23 100644 --- a/index.js +++ b/index.js @@ -10,8 +10,6 @@ const Location = require('./lib/location') const validate = require('./lib/schema-validator') const mergeSchemas = require('./lib/merge-schemas') -const SINGLE_TICK = /'/g - let largeArraySize = 2e4 let largeArrayMechanism = 'default' @@ -1074,7 +1072,7 @@ function buildConstSerializer (location, input) { ` } - code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'` + code += `json += ${JSON.stringify(JSON.stringify(schema.const))}` if (hasNullType) { code += ` diff --git a/test/const.test.js b/test/const.test.js index 48e10525..1c9182f8 100644 --- a/test/const.test.js +++ b/test/const.test.js @@ -24,6 +24,26 @@ test('schema with const string', (t) => { t.assert.ok(validate(JSON.parse(output)), 'valid schema') }) +test('schema with const string containing characters that need escaping', (t) => { + const values = ['back\\slash', 'tab\there', 'quote"here', 'new\nline', "tick's"] + t.plan(values.length * 2) + + for (const value of values) { + const schema = { + type: 'object', + properties: { + foo: { const: value } + } + } + + const stringify = build(schema) + const output = stringify({ foo: value }) + + t.assert.equal(output, JSON.stringify({ foo: value })) + t.assert.deepStrictEqual(JSON.parse(output), { foo: value }) + } +}) + test('schema with const string and different input', (t) => { t.plan(2)