Skip to content

Commit

Permalink
fix: #2482 Infinity and NaN serialise to null
Browse files Browse the repository at this point in the history
  • Loading branch information
jasoniangreen committed Aug 11, 2024
1 parent f06766f commit d7b6e92
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/compile/jtd/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
13 changes: 13 additions & 0 deletions spec/jtd-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down

0 comments on commit d7b6e92

Please sign in to comment.