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

remove trailing comma in JTD serialisation result, fixes #2001 #2028

Closed
wants to merge 6 commits into from
Closed
Changes from 2 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
25 changes: 18 additions & 7 deletions lib/compile/jtd/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,20 +156,21 @@ function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): v
const optProps = keys(optionalProperties)
const allProps = allProperties(props.concat(optProps))
let first = !discriminator
const firstProp = gen.let("first", props.length === 0)

for (const key of props) {
serializeProperty(key, properties[key], keyValue(key))
serializeProperty(key, properties[key], keyValue(key), false)
}
for (const key of optProps) {
const value = keyValue(key)
gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () =>
serializeProperty(key, optionalProperties[key], value)
serializeProperty(key, optionalProperties[key], value, true)
)
}
if (schema.additionalProperties) {
gen.forIn("key", data, (key) =>
gen.if(isAdditional(key, allProps), () =>
serializeKeyValue(cxt, key, {}, gen.let("first", first))
)
serializeKeyValue(cxt, key, {}, firstProp))
)
}

Expand All @@ -189,9 +190,19 @@ function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): v
return gen.const("value", _`${data}${getProperty(key)}`)
}

function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void {
if (first) first = false
else gen.add(N.json, str`,`)
function serializeProperty(key: string, propSchema: SchemaObject, value: Name, isOptional: boolean): void {
epoberezkin marked this conversation as resolved.
Show resolved Hide resolved
if (first) {
first = false
if (isOptional) gen.assign(firstProp, false)
} else if (isOptional) {
gen.if(
firstProp,
() => gen.assign(firstProp, false),
() => gen.add(N.json, str`,`)
)
} else {
gen.add(N.json, str`,`)
}
gen.add(N.json, str`${JSON.stringify(key)}:`)
serializeCode({...cxt, schema: propSchema, data: value})
}
Expand Down