JsonSchema

7 篇文章 0 订阅
6 篇文章 0 订阅

jsonshema用json描述json文件的格式,常用来校验json的格式;语法参见:Json Schema简介
一个在线验证网站:https://www.jsonschemavalidator.net
我在使用中主要遇到两个问题:

1. properties additionaProperties required的关系

properties描述可能出现的property格式
additionaProperties false or true表示是否可以出现比properties中列举的多余的property
required 指明哪些properties是必需的
我遇到的一个写法是:
properties 中列举了"A" “B” “C” “D”
additionaProperties 为 false
required: [“A”,“B”,“C”]
到底可不可以有"D"呢?
明白到:这就是表明"D"是可选的. required描述了最小的属性范围,propertiesadditionaProperties限制了最大的属性范围。差集就是可选的。
另一个感觉就是各种对属性的描述是独立的。

2. 如何使用继承?

如果因为一个字段的不同,同时还想要严格约束json,就只能完全重定义一遍?情景描述:
base
A: { base } + other1
B: { base + key1 } + other2
要想强制约束,即上个问题最大范围与最小范围完全一致,就要把 {base} 和 {base + key1} 完全描述,那么base就重复描述了;
否则就妥协,将 key1 最终设为可选,这时{base } + other2 也就被接受,不完备了。
当然继承的方案来了,不用重复描述可以实现强制约束:
allOf实现继承,在definition中定义一个base,
在描述A中加入 allOf:[ "$ref": "path_to_base"]
在描述B中也加入allOf:[ "$ref": "path_to_base"] , 并补充额外的properties
这里有两个约束

  1. base中不能加 additionaProperties: true,在描述具体限制的时候再限制的死死地
  2. B 中只能拓展不能override
    根据Stack Overflow上的回答,如果重复,两个限制都要生效,这是override所做不到的,一样为啥要override. How to extend a schema in JSON schema?

In this example, both schemas have a /properties/bar field. If you are thinking about this in terms of inheritance, you’re going to misunderstand what is happening here. In this case, both “/properties/bar” fields must be valid. There is no conflict to resolve. As the keyword says, “all of” the schemas must be valid. Since bar can’t possibly be both an integer and a string, no document will ever validate against the /schema/override.

评论:它们都有效,但是json不能定义一个字段既是String又是int

That’s correct. One doesn’t take precedence over the other. They both apply. Since there is no JSON document that can possibly be both a string and an integer, then nothing will ever be valid against that schema.

摘录得另一个回答说用$merge and $patch 他说这是V5的draft,我没看到这两个关键字. JSon schema and Inheritance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值