Skip to content

Commit 3ba049f

Browse files
authored
Serializing const type with ' character (#658)
* Fixed case when serializing const type with value that contains ' character * Extracted single quote as regex and used replace instead of replaceAll
1 parent cc78b2c commit 3ba049f

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

index.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ const Serializer = require('./lib/serializer')
1212
const Validator = require('./lib/validator')
1313
const Location = require('./lib/location')
1414

15+
const SINGLE_TICK = /'/g
16+
1517
let largeArraySize = 2e4
1618
let largeArrayMechanism = 'default'
1719

@@ -834,7 +836,7 @@ function buildConstSerializer (location, input) {
834836
`
835837
}
836838

837-
code += `json += '${JSON.stringify(schema.const)}'`
839+
code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'`
838840

839841
if (hasNullType) {
840842
code += `

test/const.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,26 @@ test('schema with const string and no input', (t) => {
8282
t.ok(validate(JSON.parse(output)), 'valid schema')
8383
})
8484

85+
test('schema with const string that contains \'', (t) => {
86+
t.plan(2)
87+
88+
const schema = {
89+
type: 'object',
90+
properties: {
91+
foo: { const: "'bar'" }
92+
}
93+
}
94+
95+
const validate = validator(schema)
96+
const stringify = build(schema)
97+
const output = stringify({
98+
foo: "'bar'"
99+
})
100+
101+
t.equal(output, '{"foo":"\'bar\'"}')
102+
t.ok(validate(JSON.parse(output)), 'valid schema')
103+
})
104+
85105
test('schema with const number', (t) => {
86106
t.plan(2)
87107

0 commit comments

Comments
 (0)