【问题标题】:JSON schema for an unnamed array?未命名数组的 JSON 模式?
【发布时间】:2020-03-02 23:39:00
【问题描述】:

我需要为直接在根对象中以数组形式出现的数据创建一个 JSON 模式,未命名。这种 JSON 的 MWE 将是:

{
  [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

我已经看到了验证这样一个未嵌套在对象中的数组的模式示例。我还看到了在命名数组时起作用的示例,例如

{
  vegetables : [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

第二个例子可以通过模式验证

{
  "$id": "https://example.com/arrays.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "A representation of a person, company, organization, or place",
  "type": "object",
  "properties": {
    "vegetables": {
      "type": "array",
      "items": { "$ref": "#/definitions/veggie" }
    }
  },
  "definitions": {
    "veggie": {
      "type": "object",
      "required": [ "veggieName", "veggieLike" ],
      "properties": {
        "veggieName": {
          "type": "string",
          "description": "The name of the vegetable."
        },
        "veggieLike": {
          "type": "boolean",
          "description": "Do I like this vegetable?"
        }
      }
    }
  }
}

但问题是,一旦删除了“vegetables”这个名称,我就无法找到定义有效模式的方法。如何在模式中正确表示我的数据结构?

(MWE 源自 http://json-schema.org/learn/miscellaneous-examples.html)。

【问题讨论】:

  • 基于标题而非内容的副本。其他问题表明他们使用了一个定义根元素必须是数组的模式,这个问题不是。
  • 好点@Relequestual 我撤回了接近投票。

标签: arrays json jsonschema


【解决方案1】:

您要查找的架构如下:

{
   "$id":"https://example.com/arrays.schema.json",
   "$schema":"http://json-schema.org/draft-07/schema#",
   "description":"A representation of a person, company, organization, or place",
   "type":"array",
   "items":{
      "type":"object",
      "required":[
         "veggieName",
         "veggieLike"
      ],
      "properties":{
         "veggieName":{
            "type":"string",
            "description":"The name of the vegetable."
         },
         "veggieLike":{
            "type":"boolean",
            "description":"Do I like this vegetable?"
         }
      }
   }
}

您还需要修改基本数组实例,原来的(“未命名”数组)不是有效的 JSON:

[
   {
      "veggieName":"potato",
      "veggieLike":true
   },
   {
      "veggieName":"broccoli",
      "veggieLike":false
   }
]

与 XML 不同,您只允许每个文档有一个根节点,在 JSON 中,您可以将类型或数组作为根类型。

【讨论】:

  • 问题在于这不验证,jsonschemavalidator.net 说“解析 JSON 消息时出错:无效的属性标识符字符:[。”
  • 谢谢!这也解释了为什么我在文档中找不到这种情况的解释或示例。我会调查一下我的输入是如何无效的。
猜你喜欢
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
相关资源
最近更新 更多