是否可以编写一个通用的 JSON 模式?
Is it possible to write a generic JSON Schema?
在我的根 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 模式来验证任何内部对象,而不是具体说明它们是哪些对象,例如我不关心我们有 "Name" 或 "Age",我关心我们有适当的字符串对象和数字对象。
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 两种不同类型的对象。我想知道是否有一种方法可以编写 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 模式来验证任何内部对象,而不是具体说明它们是哪些对象,例如我不关心我们有 "Name" 或 "Age",我关心我们有适当的字符串对象和数字对象。
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"]
}
参考资料