Skip to content

Commit 7d85c30

Browse files
committed
JSchema: computed default values also for empty object
1 parent b7857dd commit 7d85c30

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

jschema/__tests__/jschema_initial_data.test.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,4 +521,80 @@ describe('jschema_intial_data', () => {
521521
);
522522
expect(data).deep.eq({ foo: [1, 1] });
523523
});
524+
525+
it('Compute default for null initial value', async function () {
526+
const data = getJsonSchemaData(
527+
{
528+
title: 'test',
529+
type: 'object',
530+
properties: {
531+
foo: {
532+
default: 1,
533+
type: 'number'
534+
}
535+
}
536+
},
537+
'pydantic_v2',
538+
null
539+
);
540+
expect(data).deep.eq({ foo: 1 });
541+
});
542+
543+
it('Compute default for undefined initial value', async function () {
544+
const data = getJsonSchemaData(
545+
{
546+
title: 'test',
547+
type: 'object',
548+
properties: {
549+
foo: {
550+
default: 1,
551+
type: 'number'
552+
}
553+
}
554+
},
555+
'pydantic_v2',
556+
undefined
557+
);
558+
expect(data).deep.eq({ foo: 1 });
559+
});
560+
561+
it('Compute default for empty object initial value', async function () {
562+
const data = getJsonSchemaData(
563+
{
564+
title: 'test',
565+
type: 'object',
566+
properties: {
567+
foo: {
568+
default: 1,
569+
type: 'number'
570+
}
571+
}
572+
},
573+
'pydantic_v2',
574+
{}
575+
);
576+
expect(data).deep.eq({ foo: 1 });
577+
});
578+
579+
it('Does not compute default for populated initial value', async function () {
580+
const data = getJsonSchemaData(
581+
{
582+
title: 'test',
583+
type: 'object',
584+
properties: {
585+
foo: {
586+
default: 1,
587+
type: 'number'
588+
},
589+
bar: {
590+
default: 2,
591+
type: 'number'
592+
}
593+
}
594+
},
595+
'pydantic_v2',
596+
{ foo: 5 }
597+
);
598+
expect(data).deep.eq({ foo: 5, bar: null });
599+
});
524600
});

jschema/src/lib/components/jschema_initial_data.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import { getAllObjectProperties, isTuple } from './property_utils.js';
77
* @param {any} initialValue
88
*/
99
export function getJsonSchemaData(jsonSchema, schemaVersion, initialValue = undefined) {
10-
return getPropertyData(jsonSchema, schemaVersion, true, initialValue, initialValue === undefined);
10+
const loadDefaults =
11+
initialValue === undefined || initialValue === null || Object.keys(initialValue).length === 0;
12+
return getPropertyData(jsonSchema, schemaVersion, true, initialValue, loadDefaults);
1113
}
1214

1315
/**

0 commit comments

Comments
 (0)