quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

How to ignore unwanted `"$schema"` property in the generated code?

Open mean-ui-thread opened this issue 10 months ago • 5 comments

My problem originated when I wanted to use a "$schema" in my JSON data, which gives Visual Studio Code users a better quality of life: Each fields could emit a pop-up describing what it is when "description" is present in the schema file, and also provides improved auto-completion, highlights errors including when required fields are missing, or if there is a typo, or using an enum value that isn't valid, or failing a string pattern or number ranges, etc etc

{
  "$schema": "./PersonSchema.json",
  "firstName": "Mean",
  "middleName: "UI",
  "lastName": "Thread",
  "age": 42
}

The problem is, I want to enforce my schema as strictly as possible, not allowing unknown properties, so I am setting "additionalProperties" to false. Unfortunately, the generated Convert(json: string) function will throw an exception because of the unknown "$schema" field found in my json data.

This forces me to add a $schema property in my PersonSchema.json :

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$ref": "#/definitions/Person",
  "definitions": {
    "Person": {
      "type": "object",
      "additionalProperties": false, // <--------------- IMPORTANT TO ME
      "properties": {
        "$schema": {  "type": "string" },  // <-------------------------- HERE
        "firstName": {  "type": "string" },
        "middleName": {  "type": "string" },
        "lastName": {  "type": "string" },
        "age": { "type": "number" }
      }
    }
  }
}

which ends up code-generating this property in typescript for example:

export interface Person {
    schema?: string; // <--------------------------- HERE
    firstName?: string;
    middleName?: string;
    lastName?: string;
    age?: number;
}

Is there a way to skip $schema from being code-generated in the typescript interface without setting "additionalProperties" to true?

Ultimately, I would like this to fail:

{
  "$schema": "./PersonSchema.json",
  "firstName": "Mean",
  "middleName: "UI",
  "lastName": "Thread",
  "age": 42,
  "color": "blue"  // <----------------- this random data field that isn't part of the schema should not be allowed and should fail
}

And I would like my interface to look like this without any "$schema" properties:

export interface Person {
    firstName?: string;
    middleName?: string;
    lastName?: string;
    age?: number;
}

Thanks!

mean-ui-thread avatar Sep 23 '23 17:09 mean-ui-thread