首页 > 解决方案 > 如何验证 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.CommandsParameter.Device Initial Settings.MPU calibrate value - Gyro X)定义固定模式

我也无法更改 JSON。

感谢您的任何提示。

标签: jsonjsonschema

解决方案


JSON Schema 非常优雅地处理递归结构。如果我正确理解您的问题,这应该可以解决问题。

{
  "anyOf": [
    { ... leaf schema ... },
    {
      "type": "object",
      "patternProperties": {
        "": { "$ref": "#" }
      }
    }
  ]
}

第一个选择声明叶子,第二个选择是一个分支,它可以是另一个分支或终止于一个叶子,尽可能地递归。

注意:有些人更喜欢使用additionalProperties而不是patternProperties. 尽管它有点冗长,但我更喜欢它,因为与 不同additionalProperties的是,验证行为patternProperties不能被其他关键字修改。


推荐阅读