使用 JSON 模式为名为 "type" 的 属性 创建类型定义

Creating a type definition for a property named "type" using JSON schema

我正在尝试为现有的 JSON 文件创建一个 JSON 架构,看起来像这样:

{
  "variable": {
    "name": "age",
    "type": "integer"
  }
}

在架构中,我想确保 type 属性 的值为 stringinteger:

{
  "variable": {
    "name": "string",
    "type": {
      "type": "string",
      "enum": ["string", "integer"]
    }
  }
}

不幸的是它爆炸了消息:ValidationError {is not any of [subschema 0]...

我读到在 JSON 架构中有 "no reserved words",所以我假设一种类型是有效的,假设我正确地声明了它?

根据 the specification,在 typeValid types 部分:

The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique. String values MUST be one of the seven primitive types defined by the core specification.

稍后,在 Conditions for successful validation:

An instance matches successfully if its primitive type is one of the types defined by keyword. Recall: "number" includes "integer".

你的情况:

{
  "variable": {
    "name": "string",
    "type": ["string", "integer"]  
  }
}

jruizaranguren 接受的答案实际上并没有回答问题。

问题是给定 JSON(不是 JSON 模式,JSON 数据)有一个名为“type”的字段,很难编写 JSON不会窒息的架构。

假设您有一个现有的 JSON 数据馈送(数据,而不是架构),其中包含:

"ids": [ { "type": "SSN", "value": "123-45-6789" },
         { "type": "pay", "value": "8675309" } ]

我在尝试解决相同问题时发现的是,而不是将

"properties": {
                    "type": {                 <======= validation chokes on this 
                        "type": "string"
}

你可以放

"patternProperties": {
                    "^type$": {
                        "type": "string"
}

但我仍在研究如何将其标记为必填字段。这可能是不可能的。

我认为,基于查看原始问题中的“架构”,JSON 架构从那时起已经发展了很多 - 但这仍然是一个问题。可能会有更好的解决方案。