diff --git a/index.js b/index.js index 2c08bfba..f2a0d98a 100644 --- a/index.js +++ b/index.js @@ -12,6 +12,8 @@ const Serializer = require('./lib/serializer') const Validator = require('./lib/validator') const Location = require('./lib/location') +const SINGLE_TICK = /'/g + let largeArraySize = 2e4 let largeArrayMechanism = 'default' @@ -834,7 +836,7 @@ function buildConstSerializer (location, input) { ` } - code += `json += '${JSON.stringify(schema.const)}'` + code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'` if (hasNullType) { code += ` diff --git a/test/const.test.js b/test/const.test.js index c0b0b0aa..644c27f6 100644 --- a/test/const.test.js +++ b/test/const.test.js @@ -82,6 +82,26 @@ test('schema with const string and no input', (t) => { t.ok(validate(JSON.parse(output)), 'valid schema') }) +test('schema with const string that contains \'', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: "'bar'" } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: "'bar'" + }) + + t.equal(output, '{"foo":"\'bar\'"}') + t.ok(validate(JSON.parse(output)), 'valid schema') +}) + test('schema with const number', (t) => { t.plan(2)