首页 > 解决方案 > 使用 tv4 或任何其他验证器的 JSON Schema 验证

问题描述

我在数组中有某种 JSON 结构。要求是:

1. All the JSON object within the array can be optional.
2. Each JSON can have its own set of properties and can be complex and nested.
3. Each JSON object will have a set of mandatory attributes.

如何为此类 JSON 创建模式。使用 anyOf 或定义会有帮助吗?

更新:我有一个 JSON 对象数组,其中每个对象可以有不同的属性。唯一常见的属性是“类型”,其有效值为:电子产品、家具或金融。所以我的问题是如何派生模式?

例子

{
 "list": [
  {
   "type": "electronics"
  },
  {
   "type": "furniture"
  },
  {
   "accessRights": "readOnly",
   "rules": ['print','copy'],
   "type": "finance"
  }
}

解决方案

{
"properties": {
    "list": {
        "type": "array",
        "items": {
            "type": "object",
            "required": ["type"],
            "properties": {
                "type": {
                    "type": "string",
                    "enum": ["electronics", "furniture", "finance"]
                }
            },
            "anyOf": [{
                "properties": {
                    "type": {
                        "enum": ["electronics"]
                    }
                }
            }, {
                "properties": {
                    "type": {
                        "enum": ["furniture"]
                    }
                }
            }, {
                "properties": {
                    "type": {
                        "enum": ["finance"]
                    },
                    "accessRights": {
                        "type": "string"
                    },
                    "rules": {
                        "type": "array"
                    }
                }
            }]
        }
    }
 }
}

标签: jsonjsonschematv4

解决方案


推荐阅读