我有一个json对象,它可以包含任意数量的具有特定规范的嵌套对象,例如:

{
  "Bob": {
    "age": "42",
    "gender": "male"
  },
  "Alice": {
    "age": "37",
    "gender": "female"
  }
}

And would like to have a schema looking something like:

{
  "type": "object",
  "propertySchema": {
    "type": "object",
    "required": [
      "age",
      "gender"
    ],
    "properties": {
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}

I know that I can turn that into array and push 'name' inside the objects. In that case my schema would look like:

{
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "name",
      "age",
      "gender"
    ],
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}

but I would like to have a dictionary-like structure. Is it possible to make such schema?

推荐答案

additionalProperties is your keyword:

{
    "type" : "object",
    "additionalProperties" : {
        "type" : "object",
        "required" : [
            "age",
            "gender"
        ],
        "properties" : {
            "age" : {
                "type" : "string"
            },
            "gender" : {
                "type" : "string"
            }
        }
    }
}

additionalProperties可以具有具有不同含义的下列值:

  • "additionalProperties": false No more properties are allowed at all.
  • 允许其他"additionalProperties": true个属性.这是默认行为.
  • "additionalProperties": {"type": "string"} Additional properties (of arbitrary name) are allowed, as long as their value follows the given type ("string" here).
  • "additionalProperties": {*any schema*}个附加属性必须满足提供的模式,例如上面提供的示例.

Json相关问答推荐

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

如何在PowerShell中扩展JSON中的嵌套数组

VBA json按特定属性名称提取所有数据

如何使用PowerShell从ExchangeOnline命令执行中获得JSON输出

交换键和数组值,将旧键转换为新数组值,使用 jq

jq - 仅在键值对存在的地方打印值

如何在 JSonPath 中按值查找列表中的所有元素

jq - 将父键值提取为子元素旁边的逗号分隔值

jq: Select 何时来自另一个数组的值与此 json 中的值匹配

如何 Select 一个值,这是可选的 - 使用 jq

嵌套存储在字符串变量中的 JSON 对象

JOLT 获取带有动态键的数组

Vue 3如何将参数作为json发送到axios get

在 postgresql 中将行转换为 json 对象

Swift:如何从字典中删除空值?

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

从多维数组数据生成json字符串

在 Qt 4.7 中解析 JSON 的最简单方法

使用 Python 3 读取 JSON 文件

将 JsonArray 添加到 JsonObject