使用递归结构验证json

问题描述 投票:0回答:1

我正在寻找一种使用 json-schema 验证以下 json 的方法。

{
    "type": "node",
    "members": [
       "A",
       "B"
    ],
    "A": {
       "type": "node",
       "members": [
          "AA",
          "AB"
       ],
       "AA": {
        "type": "leaf"
       },
       "AB": {
        "type": "leaf",
        "1qola": "world"
       },
       "1itn9": 10
    },
    "B": {
        "type": "leaf"
    },
    "w81av": 5,
    "qm8yv": "hello"
}

结构是一棵树。每个成员可以是

node
leaf
类型,并包含任意数量的子成员和任意属性(例如,json 中的
w81av
1qola
)。

如何验证

members
字段(子成员姓名列表)?到目前为止,我已经提出了以下 json-schema。

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "type": {
            "type": "string",
            "enum": ["node", "leaf"]
        },
        "members": {
            "type": "array",
            "items": {
                "type": "string"
            }
        }
    },
    "additionalProperties": {
        "anyOf": [
            {
                "$ref": "#"
            },
            {
                "type": ["boolean", "number", "string"]
            }
        ]
    },
    "required": ["type"]
  }

json jsonschema
1个回答
0
投票

如何验证成员字段(子成员姓名列表)?

我希望您的意思是您希望数据中的

members
属性成为值中额外属性 (
additionalProperties
) 的数组,对吗?

JSON Schema 不支持这种内省,所以不幸的是,这不是仅用 JSON Schema 就能完成的事情。

您可以获得的最接近的是我的数据词汇表,使用 JSON 路径作为参考值。 但即便如此,JSON Path 也没有返回键列表的语法。

您需要在代码中验证这一点。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.