Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - JSON payload validates against schema even though field is missing

I assume I've missed something in defining the schema. Note that the id property is required under the form property, but it is not provided in the JSON, yet the JSON validates correctly according to multiple JSON validators online.

Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.biz",
  "type": "object",
  "properties": {
    "form": {
      "type": "object",
      "nullable": false,
      "properties": {
        "id": {
          "type": "number",
          "description": "The unique identifier of the form.",
          "nullable": false
        },
        "name": {
          "type": "string",
          "description": "The name of the form.",
          "nullable": false
        }
      }
    }
  }
}

JSON Payload

{
  "form": {
    "name": "Test 2"
  }
}
question from:https://stackoverflow.com/questions/65617304/json-payload-validates-against-schema-even-though-field-is-missing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your schema doesn't specify which properties are required. You need to set required to the fields you want to be there. You may also wish to set additionalProperties to false.

Docs: https://json-schema.org/understanding-json-schema/reference/object.html#required-properties

I don't see nullable as a key anywhere in the json schema docs.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.biz",
  "type": "object",
  "properties": {
    "form": {
      "type": "object",
      "properties": {
        "id": {
          "type": "number",
          "description": "The unique identifier of the form."
        },
        "name": {
          "type": "string",
          "description": "The name of the form."
        }
      },
      "required": ["id", "name"],
      "additionalProperties": false
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...