使用 JSON 架构为名为“type”的属性创建类型定义

All*_*ate 5 json jsonschema

我正在尝试为现有 JSON 文件创建一个 JSON 架构,如下所示:

{
  "variable": {
    "name": "age",
    "type": "integer"
  }
}
Run Code Online (Sandbox Code Playgroud)

在架构中,我想确保该type属性具有值stringinteger

{
  "variable": {
    "name": "string",
    "type": {
      "type": "string",
      "enum": ["string", "integer"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我读到 JSON 模式中没有“保留字”,所以我假设某种类型是有效的,假设我声明它正确?

Wal*_*alt 5

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

问题是,给定具有名为“type”字段的 JSON(不是 JSON 模式,JSON 数据),很难编写不会阻塞的 JSON 模式。

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

"ids": [ { "type": "SSN", "value": "123-45-6789" },
         { "type": "pay", "value": "8675309" } ]
Run Code Online (Sandbox Code Playgroud)

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

"properties": {
                    "type": {                 <======= validation chokes on this 
                        "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

你可以把

"patternProperties": {
                    "^type$": {
                        "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

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

我认为,根据原始问题中的“模式”,JSON 模式从那时起已经发展了很多 - 但这仍然是一个问题。可能有更好的解决方案。


jru*_*ren 1

根据规范,在Valid types以下部分中type

该关键字的值必须是字符串或数组。如果它是一个数组,则数组的元素必须是字符串并且必须是唯一的。字符串值必须是核心规范定义的七种基本类型之一。

后来,在Conditions for successful validation

如果实例的原始类型是关键字定义的类型之一,则实例匹配成功。回想一下:“数字”包括“整数”。

在你的情况下:

{
  "variable": {
    "name": "string",
    "type": ["string", "integer"]  
  }
}
Run Code Online (Sandbox Code Playgroud)