diff --git a/index.js b/index.js index 1bcb115d..b32e3d05 100644 --- a/index.js +++ b/index.js @@ -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) @@ -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))} } ` diff --git a/test/json-add-comma.test.js b/test/json-add-comma.test.js new file mode 100644 index 00000000..a90cc1ec --- /dev/null +++ b/test/json-add-comma.test.js @@ -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"}') +})