oneOf 对象的 Json Schema 示例

标签 json schema jsonschema

我试图通过构建一个验证两种不同对象类型的模式来弄清楚 oneOf 是如何工作的。例如一个人(名字、姓氏、运动)和车辆(类型、成本)。

以下是一些示例对象:

{"firstName":"John", "lastName":"Doe", "sport": "football"}

{"vehicle":"car", "price":20000}

问题是我做错了什么以及如何解决它。这是架构:

{
    "description": "schema validating people and vehicles", 
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": [ "oneOf" ],
    "properties": { "oneOf": [
        {
            "firstName": {"type": "string"}, 
            "lastName": {"type": "string"}, 
            "sport": {"type": "string"}
        }, 
        {
            "vehicle": {"type": "string"}, 
            "price":{"type": "integer"} 
        }
     ]
   }
}

当我尝试在这个解析器中验证它时:

https://json-schema-validator.herokuapp.com/

我收到以下错误:

   [ {
  "level" : "fatal",
  "message" : "invalid JSON Schema, cannot continue\nSyntax errors:\n[ {\n  \"level\" : \"error\",\n  \"schema\" : {\n    \"loadingURI\" : \"#\",\n    \"pointer\" : \"/properties/oneOf\"\n  },\n  \"domain\" : \"syntax\",\n  \"message\" : \"JSON value is of type array, not a JSON Schema (expected an object)\",\n  \"found\" : \"array\"\n} ]",
  "info" : "other messages follow (if any)"
}, {
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/oneOf"
  },
  "domain" : "syntax",
  "message" : "JSON value is of type array, not a JSON Schema (expected an object)",
  "found" : "array"
} ]

最佳答案

试试这个:

{
    "description" : "schema validating people and vehicles",
    "type" : "object",
    "oneOf" : [
       {
        "type" : "object",
        "properties" : {
            "firstName" : {
                "type" : "string"
            },
            "lastName" : {
                "type" : "string"
            },
            "sport" : {
                "type" : "string"
            }
          }
      }, 
      {
        "type" : "object",
        "properties" : {
            "vehicle" : {
                "type" : "string"
            },
            "price" : {
                "type" : "integer"
            }
        },
        "additionalProperties":false
     }
]
}

关于oneOf 对象的 Json Schema 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25014650/

相关文章:

javascript - 数据不显示

javascript - JSON 文件中的数据未在 html 中显示

javascript - JS读取json文件并作为对象使用

sql - postgres跨模式查询使用UNION ALL

schema - 星型模式是非规范化模式吗?

mysql - 为拥有多个学校类(class)的用户进行架构设计

jsonschema - 使用额外的必填字段扩展 $ref

javascript - 在 JSON 中查找多次出现的特定值

c# - 使用 Json.NET JsonSchemaGenerator 将 JSON Schema 属性(标题、描述)添加到 C# 类属性

jsonschema - 如何扩展 json 模式元模式以支持新属性?