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

如何配置JSON Schema:无元素时不保留数组字段,禁用空对象数组

JSON Schema for Validating Quantity with Optional Non-Empty Modifiers

Got it, let's build the JSON Schema that fits your exact validation requirements. Here's a solution that covers all your cases, along with explanations of how each part works:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["quantity"],
  "properties": {
    "quantity": {
      "type": "integer"
    },
    "modifiers": {
      "type": "array",
      "items": {
        "type": "object",
        "minProperties": 1
      },
      "minItems": 1
    }
  },
  "oneOf": [
    {
      "not": {
        "required": ["modifiers"]
      }
    },
    {
      "required": ["modifiers"]
    }
  ],
  "additionalProperties": false
}

Key Validation Logic Breakdown

Let's walk through why this schema works for your rules:

  • Mandatory quantity field: The required array ensures quantity is always present and typed as an integer.
  • Prevent unexpected fields: additionalProperties: false blocks any extra fields not defined in the schema, keeping your JSON structure strict.
  • Two mutually valid cases via oneOf:
    • No modifiers allowed: The first oneOf rule uses not: {required: ["modifiers"]} to enforce that if you don't intend to add modifiers, the field shouldn't exist at all.
    • Valid modifiers required when present: The second rule makes modifiers mandatory if it's going to be included, with these checks:
      • modifiers must be an array with at least one item (minItems: 1)
      • Every object in the modifiers array must have at least one key-value pair (minProperties: 1), which directly blocks empty objects like {} in the array.

Test Cases

Let's verify against your examples:

  • Valid (no modifiers):

    {"quantity": 3}
    

    Passes: No modifiers field, meets the first oneOf condition.

  • Valid (with non-empty modifiers):

    {"quantity": 3, "modifiers": [{"testing": "some data here"}]}
    

    Passes: modifiers array contains a non-empty object, meets the second oneOf condition.

  • Invalid (empty modifier object):

    {"quantity": 3, "modifiers": [{}]}
    

    Fails: The array item fails the minProperties: 1 check for modifier objects.

Additional invalid cases that get blocked:

  • Empty modifiers array ({"quantity":3, "modifiers":[]})
  • modifiers as a non-array value ({"quantity":3, "modifiers": {}})
  • Extra fields not defined in the schema ({"quantity":3, "extraField": "test"})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:27:02