Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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 += `
Expand Down
20 changes: 20 additions & 0 deletions test/const.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Loading