英文:
How to write a schema to constrain some of the properties with one/any of the sub-schemas?
问题
name: "range_1"
step: 1
start: 0
stop: 10
和
name: "range_2"
step: 1
center: 5
span: 5
能否像这样进行验证:
properties:
name:
type: "string"
stop:
type: number
oneOf:
- start:
type: number
step:
type: number
- center:
type: number
span:
type: number
目前我在Python中使用jsonschema,但它抱怨jsonschema.exceptions.SchemaError: <the array in oneOf> is not of type 'object', 'boolean'
。
只对name
和step
进行验证,或者对所有可能的键进行验证似乎都可以工作,但对我来说都不够理想。
英文:
Can I validate both
name: "range_1"
step: 1
start: 0
stop: 10
and
name: "range_2"
step: 1
center: 5
span: 5
with something like
properties:
name:
type: "string"
stop:
type: number
oneOf:
- start:
type: number
step:
type: number
- center:
type: number
span:
type: number
For now I am using jsonschema in Python, but it complains jsonschema.exceptions.SchemaError: <the array in oneOf> is not of type 'object', 'boolean'
.
Validating against name
and step
only or validating against all possible keys apparently works but they both seem sub-optimal for me.
答案1
得分: 1
将oneOf
关键字移出properties
对象,因为properties
对象中的所有内容都被解释为数据中期望的值。
此外,最好添加一个required
属性,使这些值成为必需值。最后,如果要确保不接受其他值,可以使用additionalProperties: false
。不过,请注意,您必须在oneOf
模式中再次重复“父级”属性。有关更多信息,我建议查看此示例。
综合考虑,您可以使用以下模式(参见此处的实时示例):
---
properties:
name:
type: string
step:
type: number
oneOf:
- properties:
name: true
step: true
start:
type: number
stop:
type: number
required:
- start
- stop
additionalProperties: false
- properties:
name: true
step: true
center:
type: number
span:
type: number
required:
- center
- span
additionalProperties: false
英文:
You need to move the oneOf
keyword out of the properties
object as everything in the properties
object is interpreted as an expected value in your data.
Additionally, it makes sense to add an required
property to make the values mandatory. Finally, if you want to make sure that no other values are excepted, you can use additionalProperties: false
. Note though, that you have to repeat the "parent" properties in the oneOf
schemas again. For further reading I recommend this example.
Put all together, you could use the following schema (see live example here):
---
properties:
name:
type: string
step:
type: number
oneOf:
- properties:
name: true
step: true
start:
type: number
stop:
type: number
required:
- start
- stop
additionalProperties: false
- properties:
name: true
step: true
center:
type: number
span:
type: number
required:
- center
- span
additionalProperties: false
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论