【问题标题】:How to validate the json against a complex json schema which has multi level of references如何针对具有多级引用的复杂 json 模式验证 json
【发布时间】:2021-09-21 02:20:30
【问题描述】:

我有一个如下的 json 架构

{
  "$id": "https://example.com/arrays.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "description": "A representation of a person, company, organization, or place",
  "type": "object",
  "properties": {
    "fruits": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "vegetables": {
      "type": "array",
      "items": { "$ref": "#/$defs/veggie" }
    }
  },
  "required" : ["fruits", "vegetables"],
  "$defs": {
    "veggie": {
      "type": "object",
      "required": [ "veggieName", "veggieLike", "cropLocation"],
      "properties": {
        "veggieName": {
          "type": "string",
        },
        "veggieLike": {
          "type": "boolean",
        },
        "cropLocation" : {
          "type" : "object",
          "items" :{ "$ref" : "#/$defs/location"}
        }
      }
    },
    "location" : {
      "type" : "object",
      "required" : ["country", "state"],
      "properties" : {
        "country" : {
          "type": "string"
         },
         "state" : {
           "type": "string"
         }
       }
    }      
  }
}

当我提供如下数据时,我预计cropLocation 没有州和国家/地区属性会出现错误。但它针对该模式验证为成功。如何定义具有多级复杂对象的模式。

  "fruits": [ "apple", "orange", "pear" ],
  "vegetables": [
    {
      "veggieName" : "carrot",
      "veggieLike": true,
      "cropLocation" : {}
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false,
      "cropLocation" : {}
    }
  ]
}

我尝试了多种方法来重新构建 json 架构,但都不起作用

【问题讨论】:

    标签: json validation jsonschema


    【解决方案1】:

    错误在这里:

              "items" :{ "$ref" : "#/$defs/location"}
    

    "cropLocation" 是一个对象,但items 是一个只适用于数组的关键字。只需删除 items 关键字并将 $ref 设为 "type": "object" 的兄弟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2019-06-10
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多