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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,8 @@ const obj = {
console.log(stringify(obj)) // '{"mail":"mail@example.com"}'
```

A property set to `undefined` is left out as well. Values that JSON cannot represent (functions, symbols, objects whose `toJSON()` returns `undefined`) are written as `null` when they reach a schema without a `type`, such as `{}` or `true`. `JSON.stringify` also writes `null` for them inside arrays, but leaves the key out inside objects. Additional and pattern properties holding a function or a symbol are still left out.

<a name="defaults"></a>
#### Defaults
`fast-json-stringify` supports `default` jsonschema key in order to serialize a value
Expand Down
13 changes: 8 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,7 @@ function buildExtraObjectPropertiesSerializer (context, location, addComma, objV
if (additionalPropertiesSchema === true) {
code += `
${addComma}
json += asString(key) + JSON_STR_COLONS + JSON.stringify(value)
json += asString(key) + JSON_STR_COLONS + (JSON.stringify(value) ?? JSON_STR_NULL)
`
} else {
const propertyLocation = location.getPropertyLocation('additionalProperties')
Expand Down Expand Up @@ -1244,7 +1244,7 @@ function buildArray (context, location, input) {
if (i) {
json += JSON_STR_COMMA
}
json += JSON.stringify(obj[i])
json += JSON.stringify(obj[i]) ?? JSON_STR_NULL
}`
}
} else {
Expand Down Expand Up @@ -1334,7 +1334,7 @@ function buildArray (context, location, input) {
inlinedCode += `
for (let i = ${itemsSchema.length}; i < arrayLength_${objVar}; i++) {
!addComma_${localUid} && (addComma_${localUid} = true) || (json += JSON_STR_COMMA)
json += JSON.stringify(${objVar}[i])
json += JSON.stringify(${objVar}[i]) ?? JSON_STR_NULL
}`
}
} else {
Expand Down Expand Up @@ -1545,7 +1545,10 @@ function buildSingleTypeSerializer (context, location, input) {
return buildArray(context, location, input)
}
case undefined:
return `json += JSON.stringify(${input})`
// JSON.stringify returns undefined for undefined, functions and symbols.
// Write null instead, as JSON.stringify does for array items, so the
// output stays valid JSON.
return `json += JSON.stringify(${input}) ?? JSON_STR_NULL`
default:
throw new Error(`${schema.type} unsupported`)
}
Expand Down Expand Up @@ -1872,7 +1875,7 @@ function buildValue (context, location, input) {
let schema = location.schema

if (typeof schema === 'boolean') {
return `json += JSON.stringify(${input})`
return `json += JSON.stringify(${input}) ?? JSON_STR_NULL`
}

if (schema.$ref) {
Expand Down
12 changes: 12 additions & 0 deletions test/additionalProperties.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,18 @@ test('additionalProperties set to false without declared properties ignores unma
t.assert.deepStrictEqual(JSON.parse(out), { str1: 'a' })
})

test('additionalProperties set to true writes null when toJSON returns undefined', (t) => {
t.plan(2)
const stringify = build({
type: 'object',
additionalProperties: true
})

const out = stringify({ x: { toJSON () { return undefined } }, y: 1 })
t.assert.equal(out, '{"x":null,"y":1}')
t.assert.deepStrictEqual(JSON.parse(out), { x: null, y: 1 })
})

test('extra properties skip undefined, function and symbol values and keep key order', (t) => {
const input = { 2: 'two', id: 1, a: 'x', u: undefined, f () {}, s: Symbol('s'), n_1: 3, 1: 'one', z: null }
const schemas = [
Expand Down
39 changes: 39 additions & 0 deletions test/any.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,45 @@ test('empty schema on array', (t) => {
t.assert.equal(stringify([1, true, 'hello', [], { x: 1 }]), '[1,true,"hello",[],{"x":1}]')
})

test('empty schema on array writes null for values JSON cannot represent', (t) => {
t.plan(4)

const stringify = build({
type: 'array',
items: {}
})

t.assert.equal(stringify([1, undefined, 2]), '[1,null,2]')
t.assert.equal(stringify([() => {}, Symbol('s')]), '[null,null]')
t.assert.equal(stringify(new Array(2)), '[null,null]')
t.assert.equal(build({ type: 'array' })([undefined]), '[null]')
})

test('additionalItems true writes null for values JSON cannot represent', (t) => {
t.plan(1)

const stringify = build({
type: 'array',
items: [{ type: 'integer' }],
additionalItems: true
})

t.assert.equal(stringify([1, undefined, () => {}]), '[1,null,null]')
})

test('empty schema never writes undefined', (t) => {
t.plan(3)

t.assert.equal(build({})(undefined), 'null')
t.assert.equal(build(true)(() => {}), 'null')
t.assert.equal(build({
type: 'object',
properties: {
x: {}
}
})({ x: () => {} }), '{"x":null}')
})

test('empty schema on anyOf', (t) => {
t.plan(4)

Expand Down
Loading