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

如何在Karate的JSON Schema中验证可选对象?

解决Karate Schema中可选字段listValues的匹配问题

要让listValues成为可选字段,避免部分ITEM对象不含该字段时的匹配错误,只需要在Karate的Schema定义里把它标记为可选即可,有两种常用写法:

方式一:用#?标记可选键

在字段名前添加#?前缀,表示该键是可选的,只有当响应中存在这个键时,才会验证其格式:

* def listValuesSchema = {"m_key": "#string", "m_value": "#string"}
* def itemsSchema = {
    "m_operators": "#[] #string",
    "operators": "#[] #string",
    "logicalDataType": "#string",
    "#?listValues": "#[] ##(listValuesSchema)",
    "tableName": "#string"
}
* def filterSchema = {"ITEM": {"ITEM": "#[] ##(itemsSchema)"}}
* def jsonExpected = {"filter": "#(filterSchema)"}
* match response == jsonExpected

方式二:用##optional修饰验证规则

在listValues的验证规则末尾添加##optional,表示该字段可以不存在,存在时才验证格式:

* def listValuesSchema = {"m_key": "#string", "m_value": "#string"}
* def itemsSchema = {
    "m_operators": "#[] #string",
    "operators": "#[] #string",
    "logicalDataType": "#string",
    "listValues": "#[] ##(listValuesSchema) ##optional",
    "tableName": "#string"
}
* def filterSchema = {"ITEM": {"ITEM": "#[] ##(itemsSchema)"}}
* def jsonExpected = {"filter": "#(filterSchema)"}
* match response == jsonExpected

注意事项

  • 修正原代码中listValuesSchema的语法错误:原代码末尾缺少一个闭合大括号},必须补上,否则Schema会解析失败。
  • 两种方式效果一致,可根据个人习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:52:57