JSON schema with single quote in property name fails to be processed when the property is required
Closed this issue · 0 comments
tomastauer commented
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Fastify version
5.14.1
Plugin version
No response
Node.js version
20.11.0
Operating system
Linux
Operating system version (i.e. 20.04, 11.3, 10)
22.04.4
Description
When stringifying JSON schema that has a single quote character ('
) in the name of the property and the property is required at the same time, the generated function is syntactically incorrect and the process fails.
Steps to Reproduce
const fastJson = require('fast-json-stringify');
const schema = {
title: 'Example Schema',
type: "object",
properties: {
"'": {
type: "string",
},
},
required: [
"'",
],
};
fastJson(schema, {});
will fail with
SyntaxError: missing ) after argument list
at new Function (<anonymous>)
as the code the schema is translated to is as follows:
let json = '{'
if (obj[\"'\"] !== undefined) {
json += \"\\\"'\\\":\"
if (typeof obj[\"'\"] !== 'string') {
if (obj[\"'\"] === null) {
json += '\"\"'
} else if (obj[\"'\"] instanceof Date) {
json += '\"' + obj[\"'\"].toISOString() + '\"'
} else if (obj[\"'\"] instanceof RegExp) {
json += serializer.asString(obj[\"'\"].source)
} else {
json += serializer.asString(obj[\"'\"].toString())
}
} else {
json += serializer.asString(obj[\"'\"])
}
} else {
throw new Error('\"'\" is required!')
==================^^==== here is the problem, the single quote is unescaped and collides with the single quotes used to wrap the error message
}
return json + '}'
Expected Behavior
Schema is accepted and stringified. It should be enough to escape the single quote character ('
) in the generated error message.
Expected output of the generated functions would be
throw new Error('\"\\'\" is required!')