You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JSON Schema验证包含指定必填项的字符串数组?

Enforce Required String Values in an Array with JSON Schema (Draft 07)

I get where you're stuck—your current schema does a good job restricting array elements to your allowed enum and ensuring no duplicates, but it doesn't enforce that the four mandatory values (uuid, template, createdOn, updatedOn) are always present. The required keyword works for object properties, not array elements, so we need a different approach here.

Solution: Use allOf + contains to Mandate Required Items

To make sure your array includes all four mandatory values while still sticking to your allowed enum, you can combine the allOf keyword with multiple contains rules. Each contains check verifies one mandatory value is present, and allOf ensures all these checks pass together.

Here's the revised JSON Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "56544e3c-e197-4602-8457-2c01dc6b12c5",
  "title": "The Root Schema",
  "type": "object",
  "additionalProperties": false,
  "required": ["attributes"],
  "properties": {
    "attributes": {
      "type": "array",
      "uniqueItems": true,
      "items": {
        "type": "string",
        "enum": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"]
      },
      "allOf": [
        { "contains": { "const": "uuid" } },
        { "contains": { "const": "template" } },
        { "contains": { "const": "createdOn" } },
        { "contains": { "const": "updatedOn" } }
      ]
    }
  }
}

Breakdown of Key Changes:

  • allOf: Wraps four separate validation rules, all of which must pass for the array to be valid.
  • contains + const: Each entry checks that the array includes exactly the specified mandatory string. const guarantees an exact match, while contains confirms the value appears at least once in the array.
  • We keep your original constraints: uniqueItems: true (prevents duplicate entries) and items.enum (limits array elements to your allowed list).

Validation Results:

  1. Valid instances (will pass):
    { "attributes": ["uuid", "template", "createdOn", "updatedOn"] }
    
    { "attributes": ["uuid", "template", "createdOn", "updatedOn", "fields", "elements"] }
    
  2. Invalid instance (will fail, missing updatedOn):
    { "attributes": ["uuid", "template", "createdOn", "fields", "elements"] }
    

This setup hits both your requirements: it ensures all mandatory values are present, and only allows the enum values you specified in the array.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:22:27