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
10 changes: 6 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,12 +369,14 @@ function buildInnerObject (context, location) {
code += 'let json = JSON_STR_BEGIN_OBJECT\n'

let addComma = ''
if (!hasRequiredProperties) {
const hasComma = !hasRequiredProperties && (propertiesKeys.length > 1 || (schema.patternProperties || schema.additionalProperties !== false))
if (hasComma) {
code += 'let addComma = false\n'
addComma = '!addComma && (addComma = true) || (json += JSON_STR_COMMA)'
}

for (const key of propertiesKeys) {
for (let i = 0; i < propertiesKeys.length; i++) {
const key = propertiesKeys[i]
let propertyLocation = propertiesLocation.getPropertyLocation(key)
if (propertyLocation.schema.$ref) {
propertyLocation = resolveRef(context, propertyLocation)
Expand All @@ -387,14 +389,14 @@ function buildInnerObject (context, location) {
code += `
value = obj[${sanitizedKey}]
if (value !== undefined) {
${addComma}
${i > 0 ? addComma : (hasComma ? 'addComma = true' : '')}
json += ${JSON.stringify(sanitizedKey + ':')}
${buildValue(context, propertyLocation, 'value')}
}`

if (defaultValue !== undefined) {
code += ` else {
${addComma}
${i > 0 ? addComma : (hasComma ? 'addComma = true' : '')}
json += ${JSON.stringify(sanitizedKey + ':' + JSON.stringify(defaultValue))}
}
`
Expand Down
57 changes: 57 additions & 0 deletions test/json-add-comma.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use strict'

const { test } = require('node:test')
const build = require('..')

test('additionalProperties: false', (t) => {
t.plan(1)
const stringify = build({
title: 'additionalProperties',
type: 'object',
properties: {
foo: {
type: 'string'
}
},
additionalProperties: false
})

const obj = { foo: 'a', bar: 'b', baz: 'c' }
t.assert.equal(stringify(obj), '{"foo":"a"}')
})

test('additionalProperties: {}', (t) => {
t.plan(1)
const stringify = build({
title: 'additionalProperties',
type: 'object',
properties: {
foo: {
type: 'string'
}
},
additionalProperties: {}
})

const obj = { foo: 'a', bar: 'b', baz: 'c' }
t.assert.equal(stringify(obj), '{"foo":"a","bar":"b","baz":"c"}')
})

test('additionalProperties: {type: string}', (t) => {
t.plan(1)
const stringify = build({
title: 'additionalProperties',
type: 'object',
properties: {
foo: {
type: 'string'
}
},
additionalProperties: {
type: 'string'
}
})

const obj = { foo: 'a', bar: 'b', baz: 'c' }
t.assert.equal(stringify(obj), '{"foo":"a","bar":"b","baz":"c"}')
})