json - 如何验证 jsonschema 中的变量嵌套对象?
问题描述
我需要为这样的结构创建一个模式:
{
"DeviceControl": {
"Commands": {
"BitLength": 8,
"Remark": "130=Restore device parameters to factory defaults,134=Calibrate gyro sensor,4=PDout come from IO-Link,128=PDout come from UART,165=Calibrate vacuum sensor,167=Reset erasable counter,168=Reset voltage min/max (Sensor & Actor) & Temperature,169=Reset vacuum min/max",
"ParameterDescriptor": "130=Restore device parameters to factory defaults,134=Calibrate gyro sensor,4=PDout come from IO-Link,128=PDout come from UART,165=Calibrate vacuum sensor,167=Reset erasable counter,168=Reset voltage min/max (Sensor & Actor) & Temperature,169=Reset vacuum min/max",
"Range": "130,134,4,128,165,167,168,169"
}
},
"Parameter": {
"Device Initial Settings": {
"MPU calibrate value - Gyro X": {
"Index": 303,
"Label": "MPU calibrate value - Gyro X",
"DataType": "IntegerT",
"BitLength": 16
},
"MPU calibrate value - Gyro Y": {
"Index": 304,
"Label": "MPU calibrate value - Gyro Y",
"DataType": "IntegerT",
"BitLength": 16
}
}
}
}
我遇到的问题是“BigLength、Remark、ParameterDescriptor 等”的架构。我可以很容易地定义。但是我如何将它应用于所有对象,直到它找到这个模式?它可以是任何深度嵌套的东西。当没有更多对象作为子对象时,它应该应用此模式。不可能为所有对象键(DeviceControl.Commands
或Parameter.Device Initial Settings.MPU calibrate value - Gyro X
)定义固定模式
我也无法更改 JSON。
感谢您的任何提示。
解决方案
JSON Schema 非常优雅地处理递归结构。如果我正确理解您的问题,这应该可以解决问题。
{
"anyOf": [
{ ... leaf schema ... },
{
"type": "object",
"patternProperties": {
"": { "$ref": "#" }
}
}
]
}
第一个选择声明叶子,第二个选择是一个分支,它可以是另一个分支或终止于一个叶子,尽可能地递归。
注意:有些人更喜欢使用additionalProperties
而不是patternProperties
. 尽管它有点冗长,但我更喜欢它,因为与 不同additionalProperties
的是,验证行为patternProperties
不能被其他关键字修改。
推荐阅读
- html - 是否可以在纯 HTML 中根据条件隐藏标签?
- python - 从列表创建密钥对并附加到列表列表
- javascript - 我自己的外部 js 代码在 react-router 中工作一次
- dynamics-crm - 查找用于通过 ADFS 登录的浏览器
- python - 我想根据它们的“ index = somevalue”添加同一列中存在的两个单元格的值
- r - 将 R 函数从 dplyr 转换为 data.table
- kubernetes - Azure AKS 节点池未缩放
- c#-8.0 - 这是公共但抽象的接口方法预期的行为吗?
- python - 我想用python替换xml中的一个空节点
- grails - 如何在 grails 中读取 src/main/resources 中的文件