如何在JSON Schema中从指定对象选取特定字段?
按字段值定位数组对象的JSON Schema路径写法
要在JSON Schema中忽略数组对象顺序,根据唯一的TypeId值(如230098)获取对应对象的memberAmount字段,有两种常用实现方式:
方式1:使用JSONPath直接过滤(工具兼容时优先用)
如果你的JSON验证工具支持JSONPath语法,可以直接用带条件过滤的路径定位目标字段,写法如下:
MapList.Object[?(@.TypeId == 230098)].memberAmount
这个路径会直接匹配数组中TypeId等于230098的对象,无论它在数组中的位置如何,都能准确获取memberAmount的值。
方式2:结合JSON Schema的contains和$data关键字
如果需要严格遵循JSON Schema规范(Draft 2019-09及以上版本),可以先通过contains定位符合条件的对象,再用$data引用其字段:
完整Schema示例
{ "type": "object", "properties": { "MapList": { "type": "object", "properties": { "Object": { "type": "array", // 定位TypeId为230098的对象 "contains": { "type": "object", "properties": { "TypeId": {"const": 230098}, "memberAmount": {"type": "number"} }, "required": ["TypeId", "memberAmount"] } } }, "required": ["Object"] } }, // 示例:验证某个字段与目标memberAmount相等 "properties": { "verifiedAmount": { "type": "number", "const": {"$data": "#/properties/MapList/properties/Object/contains/properties/memberAmount"} } } }
这里通过contains确保数组中存在TypeId为230098的对象,再用$data关键字引用该对象的memberAmount,实现与数组顺序无关的字段引用。
注意点
$data关键字需要JSON Schema Draft 2019-09及以上版本支持,使用前确认你的验证工具是否兼容。- JSONPath的写法更简洁直观,大部分现代JSON验证库(如Ajv的JSONPath插件)都支持这种语法。
内容的提问来源于stack exchange,提问作者Muazzam
相关产品推荐
相关产品推荐

