简体   繁体   English

JSON 模式验证问题(patternProperties)

[英]Problem with JSON schema validation (patternProperties)

I ran into the problem of compiling a JSON schema for a similar REST API response.我遇到了为类似的 REST API 响应编译 JSON 架构的问题。 I use https://ajv.js.org / for schema validation.我使用https://ajv.js.org / 进行模式验证。

"2014" is the year, "6" is the month of the year “2014”是年份,“6”是年份中的月份

There may be different years in this scheme and there may be different months in each year.该计划可能有不同的年份,并且每年可能有不同的月份。 There is no strict sequence.没有严格的顺序。

I have run out of ideas on how to correctly describe such a scheme in order to control the correctness of the spelling of the year and month (if the answer comes "22", instead of "2022", then it will be a big problem)我已经没有关于如何正确描述这样一个方案以控制年份和月份拼写正确性的想法(如果答案是“22”,而不是“2022”,那么这将是一个大问题)

I tried "patternProperties" (ajv), but it doesn't give a result.我尝试了“patternProperties”(ajv),但没有给出结果。 I will be glad of any good idea or hint.我会很高兴有任何好主意或提示。 Thanks.谢谢。

{
    "2014": {
        "6": [
            {
                "code": "code1",
                "name": "item1"
            },
            {
                "code": "code2",
                "name": "item2"
            },
        ],
        "7": [
            {
                "code": "code1",
                "name": "item1"
            },
            {
                "code": "code1",
                "name": "item2"
            },
        ],
    }
    "2020": {
        "2": [
            {
                "code": "code1",
                "name": "item1"
            },
            {
                "code": "code2",
                "name": "item2"
            },
        ],
        "11": [
            {
                "code": "code1",
                "name": "item1"
            },
            {
                "code": "code1",
                "name": "item2"
            },
        ],
    }
}

This will give you the last two numbers of the year every time and will help you prevent the problem you described if the years in your object are 100 years apart.如果 object 中的年份相隔 100 年,这将为您提供每年的最后两个数字,并将帮助您防止您描述的问题。 More than that will probably require a whole load of regex for greater precision.不仅如此,可能还需要大量的正则表达式才能获得更高的精度。

const obj = {
 2014: {
  6: [
   {
    code: "code1",
    name: "item1",
  },
 ],
},
14: {
 11: [
  {
   code: "code1",
   name: "item1",
  },
 ],
},
};

for (const [key, value] of Object.entries(obj)) {
 const numbers = key.split("");
 const year = numbers[numbers.length - 2] + "" + numbers[numbers.length - 1];

 console.log(year);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM