Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: #2482 Infinity and NaN serialise to null #2487

Merged
merged 7 commits into from
Sep 15, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,14 @@ Defines how date-time strings are parsed and validated. By default Ajv only allo
This option makes JTD validation and parsing more permissive and non-standard. The date strings without time part will be accepted by Ajv, but will be rejected by other JTD validators.
:::

### specialNumbers <Badge text="JTD only" />
jasoniangreen marked this conversation as resolved.
Show resolved Hide resolved

Defines how special case numbers, Infinity, -Infinity and NaN are handled. Use `specialNumbers: "null"` to serialize them to `null` which is correct behavior according to the JSON spec. If you wish to handle these values, however, and not lose the data you can use `specialNumbers: "string"` which will serialize them to strings. If this option is not set the values will be included as the original literal values.

::: warning The default behavior can produce invalid JSON
If `specialNumbers` is left undefined, the serializer will produce invalid JSON when there are any special case numbers in the data. This is, however, the fastest mode and so should be used unless you expect to encounter special case numbers.
:::

### int32range <Badge text="JTD only" />

Can be used to disable range checking for `int32` and `uint32` types.
Expand Down
13 changes: 11 additions & 2 deletions lib/compile/jtd/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,17 @@ function serializeString({gen, data}: SerializeCxt): void {
gen.add(N.json, _`${useFunc(gen, quote)}(${data})`)
}

function serializeNumber({gen, data}: SerializeCxt): void {
gen.add(N.json, _`"" + ${data}`)
function serializeNumber({gen, data, self}: SerializeCxt): void {
const condition = _`${data} === Infinity || ${data} === -Infinity || Number.isNaN(${data})`
const addNumber = (): CodeGen => gen.add(N.json, _`"" + ${data}`)

if (self.opts.specialNumbers === "null") {
gen.if(condition, () => gen.add(N.json, _`null`), addNumber)
} else if (self.opts.specialNumbers === "string") {
gen.if(condition, () => gen.add(N.json, str`"${data}"`), addNumber)
} else {
addNumber()
}
Copy link
Member

@epoberezkin epoberezkin Aug 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

x !== x avoids function call overhead, the only advantage of Number.isNaN is clarity, but we're optimizing for performance here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

jasoniangreen marked this conversation as resolved.
Show resolved Hide resolved
}

function serializeRef(cxt: SerializeCxt): void {
Expand Down
1 change: 1 addition & 0 deletions lib/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export interface CurrentOptions {
timestamp?: "string" | "date" // JTD only
parseDate?: boolean // JTD only
allowDate?: boolean // JTD only
specialNumbers?: "string" | "null" // JTD only
$comment?:
| true
| ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
Expand Down
70 changes: 70 additions & 0 deletions spec/jtd-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,76 @@ describe("JSON Type Definition", () => {
}
})

describe("serialize special numeric values", () => {
describe("default", () => {
const ajv = new _AjvJTD()

it(`should serialize Infinity to literal`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(Infinity)
assert.equal(res, "Infinity")
assert.throws(() => JSON.parse(res))
})
it(`should serialize -Infinity to literal`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(-Infinity)
assert.equal(res, "-Infinity")
assert.throws(() => JSON.parse(res))
})
it(`should serialize NaN to literal`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(NaN)
assert.equal(res, "NaN")
assert.throws(() => JSON.parse(res))
})
})
describe("to null", () => {
const ajv = new _AjvJTD({specialNumbers: "null"})

it(`should serialize Infinity to null`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(Infinity)
assert.equal(res, "null")
assert.equal(JSON.parse(res), null)
})
it(`should serialize -Infinity to null`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(-Infinity)
assert.equal(res, "null")
assert.equal(JSON.parse(res), null)
})
it(`should serialize NaN to null`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(NaN)
assert.equal(res, "null")
assert.equal(JSON.parse(res), null)
})
})

describe("to string", () => {
const ajv = new _AjvJTD({specialNumbers: "string"})

it(`should serialize Infinity to string`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(Infinity)
assert.equal(res, '"Infinity"')
assert.equal(JSON.parse(res), "Infinity")
})
it(`should serialize -Infinity to string`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(-Infinity)
assert.equal(res, '"-Infinity"')
assert.equal(JSON.parse(res), "-Infinity")
})
it(`should serialize NaN to string`, () => {
const serialize = ajv.compileSerializer({type: "float64"})
const res = serialize(NaN)
assert.equal(res, '"NaN"')
assert.equal(JSON.parse(res), "NaN")
})
})
})

describe("parse", () => {
let ajv: AjvJTD
before(() => (ajv = new _AjvJTD()))
Expand Down