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

如何使用JSON Schema验证数组中是否存在指定字符串(允许其他元素存在)

JSON Schema: Validate Array Contains At Least One Specific String

I get exactly what you're trying to do here—you need your schema to pass only when the array includes at least one "message 1", and you don't care about any other strings in the array. The problem with your current schema is that it's enforcing every single item in the array to be "message 1", which isn't what you want.

The Fix: Use the contains Keyword

JSON Schema (draft-6 and later) has a built-in contains keyword designed exactly for this scenario—it checks that at least one element in the array matches the specified schema. Here's how to adjust your schema fragment:

"messages": {
  "type": "array",
  // Require at least one element to be exactly "message 1"
  "contains": {
    "type": "string",
    "const": "message 1"
  },
  // Allow other elements to be any string (adjust this if you have other constraints)
  "items": {
    "type": "string"
  }
}

How This Works:

  • For your first two examples (arrays that include "message 1"), the schema will pass—contains finds the matching element, and the rest of the items are valid as they're strings.
  • For the third example (no "message 1"), contains fails, so the whole schema validation fails, which is exactly what you want.

Notes for Older Schema Drafts:

If you're working with a JSON Schema draft before version 6, contains isn't available. In that case, you can use a less scalable workaround with anyOf (though this isn't ideal for arrays of unknown length):

"messages": {
  "type": "array",
  "anyOf": [
    { "items": { "const": "message 1" }, "minItems": 1 },
    { "items": [{"const": "message 1"}], "additionalItems": true },
    { "items": [{}, {"const": "message 1"}], "additionalItems": true }
    // Add more entries for each possible position of "message 1" if needed
  ]
}

Unless you have strict compatibility requirements, stick with contains—it's the clean, intended solution for this use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 18:23:11