diff --git a/lib/compile/jtd/serialize.ts b/lib/compile/jtd/serialize.ts index 1d228826d4..3a0d15fcd7 100644 --- a/lib/compile/jtd/serialize.ts +++ b/lib/compile/jtd/serialize.ts @@ -229,7 +229,11 @@ function serializeString({gen, data}: SerializeCxt): void { } function serializeNumber({gen, data}: SerializeCxt): void { - gen.add(N.json, _`"" + ${data}`) + gen.if( + _`${data} === Infinity || ${data} === -Infinity || Number.isNaN(${data})`, + () => gen.add(N.json, _`null`), + () => gen.add(N.json, _`"" + ${data}`) + ) } function serializeRef(cxt: SerializeCxt): void { diff --git a/spec/jtd-schema.spec.ts b/spec/jtd-schema.spec.ts index f4881b18a4..f3a400be19 100644 --- a/spec/jtd-schema.spec.ts +++ b/spec/jtd-schema.spec.ts @@ -146,6 +146,19 @@ describe("JSON Type Definition", () => { } }) + describe("serialize special numeric values", () => { + const ajv = new _AjvJTD() + + it(`should serialize Infinity to null`, () => { + const serialize = ajv.compileSerializer({type: "float64"}) + assert.deepStrictEqual(JSON.parse(serialize(Infinity)), null) + }) + it(`should serialize NaN to null`, () => { + const serialize = ajv.compileSerializer({type: "float64"}) + assert.deepStrictEqual(JSON.parse(serialize(NaN)), null) + }) + }) + describe("parse", () => { let ajv: AjvJTD before(() => (ajv = new _AjvJTD()))