json - 是否可以编写通用的 JSON Schema?

标签 json schema jsonschema abstraction generic-collections

在我的根 JSON 对象中,我有许多两种不同类型的 JSON 对象。我想知道是否有一种方法可以编写 JSON 模式来验证这些对象而无需获取特定的(即通用模式)。

例如,假设我有以下 JSON:

"Profile":
{
    "Name":
    {
        "Type": "String",
        "Value": "Mike",
        "Default": "Sarah",
        "Description": "This is the name of my person."
    }
    "Age":
    {
        "Type": "Number",
        "Value": 27,
        "Default": 18,
        "Description": "This is the age of my person."
    }
}

此配置文件 JSON 对象表示关于一个人的各种详细信息的集合。请注意,我有两种不同类型的内部对象,字符串对象和数字对象。考虑到这一点,我现在想创建一个 JSON 模式来验证任何内部对象,而不是具体说明它们是哪些对象,例如我不关心我们有“姓名”或“年龄”,我关心我们有适当的字符串对象和数字对象。

JSON Schema 是否提供了执行此操作的能力?如何根据我拥有的对象种类而不是特定对象名称编写通用 JSON 架构?

这是我到目前为止所得到的:

{
"$schema": "http://json-schema.org/draft-04/schema#",
  "definitions": {
    "StringObject": {
      "type": "object",
      "properties": {
        "Type": {
          "type": "string"
        },
        "Value": {
          "type": "string"
        },
        "Default": {
          "type": "string"
        },
        "Description": {
          "type": "string"
        }
      },
      "required": [
        "Type",
        "Value",
        "Default",
        "Description"
      ]
    }
  }
}

最佳答案

Inside my root JSON object I have many JSON objects of two different types. I'm wondering if there is a way to write a JSON schema to validate these objects without getting specific, i.e. generic schema.

定义联合类型来处理这个:

A value of the "union" type is encoded as the value of any of the member types.

Union type definition - An array with two or more items which indicates a union of type definitions. Each item in the array may be a simple type definition or a schema.

{
"type":
  ["string","number"]
}

引用资料

关于json - 是否可以编写通用的 JSON Schema?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36985970/

相关文章:

json - 如何解析一小段 JSON 数据而不是整个 JSON 序列

具有一些固定项目的可变长度数组的 JSON 模式

json - 元模式指定所有属性所需的属性

scala - 如何在 Spark 中创建 Schema 文件

Java:将 XML 映射到其他 XML(翻译)

json - 编写 JSON 模式以检测具有重复名称的对象

javascript - 使用 Angular 指令和 JSON 的最佳方式

android - 为 greenDao 和改造创建通用数据模型

json - 如何在需要等待内容加载的动态页面上使用 JSON-LD 添加结构化数据?

mysql - MySQL 中 INDEX、PRIMARY、UNIQUE、FULLTEXT 之间的区别?