From d7b6e9264075d9a11e130586260efe21ecd327f9 Mon Sep 17 00:00:00 2001 From: Jason Green Date: Sun, 11 Aug 2024 23:18:52 +0100 Subject: [PATCH] fix: #2482 Infinity and NaN serialise to null --- lib/compile/jtd/serialize.ts | 6 +++++- spec/jtd-schema.spec.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) 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()))