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

Here are some sample objects:

{"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"} 
        }
     ]
   }
}

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

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

I get the following error:

   [ {
  "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"
} ]

推荐答案

Try this:

{
    "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
     }
]
}

Json相关问答推荐

如何让jq输出长数据集?

需要Jolt规范将具有动态字段的输入json转换为输出json

基于两个条件替换扁平化的SON中的值

两种情况下过滤的JOLT规范

Golang JSON Date Tim.Date()测试请求

将数组中的值作为键连接到另一个数组中的值(Jolt)

数据到jsonObject到数据到 struct 是可能的吗?

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

Powershell 7.2:ConvertFrom-Json - 日期处理

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

通过一个序列化器更新多个模型数据

N1QL 聚合查询 Couchbase

如何解决名为 null 的map值

如何从 HttpClient 解析 JSON 字符串?

在 Postgres 中向 JSON 对象添加元素

C#扁平化json struct

如何将 Swift 对象转换为字典

杰克逊:反序列化 for each 值都具有正确类型的 Map

如何使用 Serde 反序列化带有自定义函数的可选字段?

使用 Codable 序列化为 JSON 时的 Swift 字符串转义