【问题标题】:JSON schema - objects with same datatypeJSON 模式 - 具有相同数据类型的对象
【发布时间】:2017-12-14 09:05:25
【问题描述】:

我生成了以下 JSON:

{
 "someString" : "example",
 "obj1" : {
     "opt1" : 1,
     "opt2" : 1,
     "opt3" : "aaa"
 },
 "obj2" : {
     "opt1" : 55,
     "opt2" : 55,
     "opt3" : "bbb"
 }
}

并且会有更多具有相同数据类型(opt1、opt2、opt3)的对象(obj1、obj2、obj3、obj4、...)

现在我想为此创建架构,但我不知道如何在架构中组合所有这些对象。

编辑:

我创建了架构:

root: {
    "type" : "object",
    "oneOf" : [
        {
        "properties" : {
            "someString" : { "type" : "string" }
        },
        "patternProperties" : { "^.*$" : { "$ref" : "./schemas/myPatternProperties.json#" } },
        "additionalProperties" : false }
        }
    ]
}

myPatternProperties.json 看起来:

{
    "type" : "object",
    "properties" : {
        "opt1" : { "type" : "number" },
        "opt2" : { "type" : "number" },
        "opt3" : { "type" : "string" },
    }
    "required" : [ "opt1", "opt2", "opt3" ]
}

有什么问题吗,因为我生成的 JSON 仍然没有被识别为这种模式类型。

【问题讨论】:

    标签: json node.js jsonschema


    【解决方案1】:

    据我了解,您的问题是 describe object with a lot of properties with the same type and some naming rules。要解决这个问题,您必须指定 patternProperties 部分

    {
        "patternProperties": {
            "^(/[^/]+)+$": { "$ref": "http://some.site.somewhere/entry-schema#" }
    }
    

    该构造为属性指定pattern to match。示例how to use patternProperties 阅读更多内容specification

    更新

    其实完整的方案一定是这样的

    {
        "$schema": "http://json-schema.org/draft-06/schema#",
        "type": "object",
        "properties": {
            "someString": {
                "type": "string"
            }
        },
        "patternProperties": {
            "^obj([0-9]+)$": {
                "$ref": "#/definitions/objEntity"
            }
        },
        "additionalProperties": false,
        "required": [ "someString" ],
    
        "definitions": {
            "objEntity": {
                "type": "object",
                "properties": {
                    "opt1": { "type": "number" },
                    "opt2": { "type": "number" },
                    "opt3": { "type": "string" }
                },
                "required": ["opt1", "opt2", "opt3"]
            }
        }
    }
    

    当然,您可以将该方案拆分为多个文件,并将链接更改为类型定义。

    【讨论】:

    • 感谢您的回复模式是我所需要的。我创建了一些架构。我想我错过了此架构中的某些内容,因为它仍然无法正常工作。
    • 您是否收到任何错误消息?您的示例数据实际上在 JSONBuddy 中验证良好。
    • 不,我不明白。要检查我使用的方案JSON Schema Validator
    • 我正在使用 Node.js 和 prettyjson 模块。我打电话: var jsonData = JSON.parse(jsonString);然后 console.log(prettyjson.render(jsonData));在输出我得到一些不正确顺序的字段。前任。没有:opt1、opt2、opt3,但由于某种原因:opt3、opt1、opt2。并且每次运行该程序时,此顺序都会发生变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2013-11-30
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多