类似字典的JSON模式

iro*_*nic 19 json dictionary jsonschema

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

{
  "Bob": {
    "age": "42",
    "gender": "male"
  },
  "Alice": {
    "age": "37",
    "gender": "female"
  }
}
Run Code Online (Sandbox Code Playgroud)

并希望有一个模式看起来像:

{
  "type": "object",
  "propertySchema": {
    "type": "object",
    "required": [
      "age",
      "gender"
    ],
    "properties": {
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以把它变成数组并在对象中推送'name'.在这种情况下,我的架构看起来像:

{
  "type": "array",
  "items": {
    "type": "object",
    "required": [
      "name",
      "age",
      "gender"
    ],
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "string"
      },
      "gender": {
        "type": "string"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我希望有一个类似字典的结构.有可能制作这样的架构吗?

jru*_*ren 34

additionalProperties是您的关键字:

{
    "type" : "object",
    "additionalProperties" : {
        "type" : "object",
        "required" : [
            "age",
            "gender"
        ],
        "properties" : {
            "age" : {
                "type" : "string"
            },
            "gender" : {
                "type" : "string"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • "additionalProperties": false 根本不允许更多属性.
  • "additionalProperties": true允许更多属性.这是默认行为.
  • "additionalProperties": {"type": "string"} 如果它们具有给定类型的值(此处为"string"),则允许其他属性(任意名称).
  • "additionalProperties": {*any schema*} 其他属性必须满足提供的架构,例如上面提供的示例.

  • 谢谢你的好回答。我添加了几行解释“additionalProperties”的不同含义。 (2认同)