首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >未命名数组的JSON模式?

未命名数组的JSON模式?
EN

Stack Overflow用户
提问于 2019-11-06 21:10:24
回答 1查看 1.2K关注 0票数 1

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

代码语言:javascript
运行
复制
{
  [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

我见过验证这种不嵌套在对象中的数组的模式的示例。我还看到过在命名数组时有效的示例,例如

代码语言:javascript
运行
复制
{
  vegetables : [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

第二个示例可以通过模式进行验证

代码语言:javascript
运行
复制
{
  "$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?"
        }
      }
    }
  }
}

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

(MWEs从http://json-schema.org/learn/miscellaneous-examples.html派生)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-06 21:20:07

您要查找的模式如下:

代码语言:javascript
运行
复制
{
   "$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:

代码语言:javascript
运行
复制
[
   {
      "veggieName":"potato",
      "veggieLike":true
   },
   {
      "veggieName":"broccoli",
      "veggieLike":false
   }
]

与XML不同的是,每个文档只能有一个根节点,而在JSON中,您可以使用类型或数组作为根类型。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58730967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档