GREsau / schemars

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

Annotate a field so it is both `required` and `default` #276

Closed Shelim closed 2 months ago

Shelim commented 7 months ago

I was unable to find a way to annotate a field, so it both:

Reasoning: I am using Vscode as JSON editor, and its intelisense can automatically put the default value of the JSON field from schema when it is created. But the field must be present in data, for the actual loader.

Visual reference (field "Name" has a default value of "Someone") - and I want it to be still required: Code_-_Insiders_TRzP0cpWx7

GREsau commented 2 months ago

The easiest way to achieve this in schemars 1.0.0-alpha.3 is by using the extend attribute, which can be used to set/override any property on the schema including default:

#[derive(JsonSchema)]
pub struct Author {
    #[schemars(extend("default" = "Someone"))]
    pub name: String,
}

produces:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Author",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "default": "Someone"
    }
  },
  "required": [
    "name"
  ]
}