本文介绍了类似于字典的JSON模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a json object that can contain any number of nested objects with certain specification, for example:

{
  "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是您的关键字:

additionalProperties is your keyword:

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

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

additionalProperties can have following values with different meanings:


  • additionalProperties:false 根本不允许使用更多属性。

  • additionalProperties:true 允许任何其他属性。这是默认行为。

  • additionalProperties:{ type: string} 其他属性(任意名称)

  • additionalProperties:{*任何模式*} 其他属性必须满足所提供的模式,例如上面提供的示例。

  • "additionalProperties": false No more properties are allowed at all.
  • "additionalProperties": true Any more properties are allowed. This is the default behavior.
  • "additionalProperties": {"type": "string"} Additional properties (of arbitrary name) are allowed, if they have value of given type ("string" here).
  • "additionalProperties": {*any schema*} Additional properties must satisfy the provided schema, such as the example provided above.

这篇关于类似于字典的JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-24 09:13