【问题标题】:Dictionary-like JSON schema类似字典的 JSON 模式
【发布时间】:2015-02-06 02:24:59
【问题描述】:

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

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

并且希望有一个看起来像这样的模式:

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

我知道我可以将其转换为数组并将“名称”推送到对象中。在这种情况下,我的架构将如下所示:

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

但我想要一个类似字典的结构。是否可以制作这样的架构?

【问题讨论】:

    标签: json dictionary jsonschema


    【解决方案1】:

    additionalProperties 是您的关键字:

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

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

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

    【讨论】:

    • 感谢您的精彩回答。我添加了几行来解释“additionalProperties”的不同含义。
    • 感谢@JanVlcinsky 改进了答案(尽管使用标题作为代码摘录对我来说似乎有点过分)。
    • 您可以随意编辑它。这就是我通知你的原因。我经常使用标题以更直观的方式传递关键信息,但我同意有时会感觉太多。
    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多