你的例子是正确的。
如何记录对象中“键”的限制?理想情况下,我想说“这不仅仅是任意字符串,它是与孩子相对应的 ID”。这是否以任何方式得到支持?
开放API 3.1
OAS 3.1 完全支持 JSON Schema 2020-12,包括patternProperties https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties。此关键字允许您使用正则表达式定义字典键的格式:
"Parent": {
"type": "object",
"patternProperties": {
"^child\d+$": {
"$ref": "#/components/schemas/Child"
}
},
"description": "A map of `Child` schemas, where the keys are IDs that correspond to the child"
}
或者,如果属性名称是由枚举定义的,您可以使用propertyNames https://json-schema.org/understanding-json-schema/reference/object.html#id4定义该枚举:
"Parent": {
"type": "object",
"propertyNames": {
"enum": ["foo", "bar"]
},
"additionalProperties": {
"$ref": "#/components/schemas/Child"
}
}
OpenAPI 3.0 和 2.0
字典键被假定为字符串,但无法限制键的内容/格式。您可以在架构中口头记录任何限制和细节description
。添加架构示例可以帮助说明您的字典/地图可能是什么样子。
"Parent": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/Child"
},
"description": "A map of `Child` schemas, where the keys are IDs that correspond to the child",
"example": {
"child1": { ... bunch of stuff ... },
"child2": { ... bunch of stuff ... },
}
如果可能的键名称已知(例如,它们是枚举的一部分),您可以将字典定义为常规对象,并将键定义为单独的对象属性:
// Keys can be: key1, key2, key3
"Parent": {
"type": "object",
"properties": {
"key1": { "$ref": "#/components/schemas/Child" },
"key2": { "$ref": "#/components/schemas/Child" },
"key3": { "$ref": "#/components/schemas/Child" }
}
}
然后你可以添加"additionalProperties": false
真正确保只使用这些密钥。