【问题标题】:json schema for a map of similar objects相似对象映射的 json 模式
【发布时间】:2014-12-08 12:27:35
【问题描述】:

我希望编写一个 json 模式来涵盖这个(简化的)示例

{
    "errorMessage": "",
    "nbRunningQueries": 0,
    "isError": False,
    "result": {
        "foo": {"price":10.0, "country":"UK"},
        "bar": {"price":100.2, "country":"UK"}
    }
}

可以有这个非常简单的根架构

schema = {
    "type":"object",
    "required":True,
    "properties":{
        "errorMessage": {"type":"string", "required":True},
        "isError": {"type":"boolean", "required":True},
        "nbRunningQueries": {"type":"number", "required":True},
        "result": {"type":"object","required":True}
    }
}

复杂的是结果 {} 元素。与标准模式不同,标准模式的结果是相同对象的数组——每个对象都有一个 id 字段或类似的字段,此响应模拟一个 Python 字典,如下所示:

{
    "foo": {},
    "bar": {},
    ...
}

既然 a 将获得一个大小灵活且没有设置键的结果对象,我该如何为此编写 json 架构?

遗憾的是,我无法控制输入,否则我会将其重写为类似

{
    "errorMessage": "",
    "nbRunningQueries": 0,
    "isError": False,
    "result": [
        {"id": "foo", "price":10.0, "country": "UK"},
        {"id": "bar", "price":100.2, "country":"UK"}
    ]
}

任何帮助或相关示例的链接都会很棒。谢谢。

【问题讨论】:

  • 结果 {} 对象的键将始终是仅包含数字的字符串......如果有帮助的话。

标签: json jsonschema


【解决方案1】:

使用 json-schema draft 4,您可以使用 additionalProperties 关键字来指定您可以在结果对象中接收到的任何新属性的架构。

"result" : {
    "type" : "object"
    "additionalProperties" : {
        "type" : "number"
    }
}

如果您可以限制允许的键名,那么您可以使用“patternProperties”关键字和正则表达式来限制允许的键名。

请注意,在 json-schema 草案 4 中,“必需”必须是绑定到对象而不是每个属性的数组。

【讨论】:

    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2018-08-18
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多