GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
791 stars 220 forks source link

Support `allowTrailingCommas` in schema #283

Closed bradzacher closed 4 weeks ago

bradzacher commented 4 months ago

https://github.com/microsoft/vscode/issues/102061#issuecomment-656541600

If you use the schema in a .jsonc file VSCode permits trailing commas, but reports a warning on them with a warning. The way to stop this behaviour is by adding the allowTrailingCommas field to the schema.

There's currently no blessed way to set this field on the schema generated by schemars - it would be great if it was supported so that the tool generating the schema could flag that it supports trailing commas in the schema.

Note that I currently use the following workaround to set it

#[derive(Serialize)]
struct RootSchemaAllowTrailingCommas {
    #[serde(flatten)]
    schema: RootSchema,
    #[serde(rename = "allowTrailingCommas")]
    allow_trailing_commas: bool,
}
GREsau commented 4 weeks ago

This is possible in schemars 1.0.0-alpha.3 using the extend attribute:

#[derive(JsonSchema)]
#[schemars(extend("allowTrailingCommas" = true))]
pub struct MyStruct {
    foo: i32,
}

produces:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "MyStruct",
  "type": "object",
  "properties": {
    "foo": {
      "type": "integer",
      "format": "int32"
    }
  },
  "allowTrailingCommas": true,
  "required": [
    "foo"
  ]
}