【问题标题】:Validate each object key in the object array with json schema in ajv使用 ajv 中的 json 模式验证对象数组中的每个对象键
【发布时间】:2019-12-09 00:10:37
【问题描述】:

我有一个数组,其中包含具有不同键值的对象。我想验证每个对象键。例如,age 字段只能获取 Equal 和 Not equal 运算符值。所以每个键的“op”键是不同的。例如,名称应与包含运算符一起使用。

[

{ age:21, op: "Equal" },
{ name:21, op: "Contains" },
{ date: 1564577662198, op: "Not equal" }

]

我已经写了一个架构,

{
  "title": "ValidatorSchema",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "age":{
        "type": "number"
      },
      "operator" : {
        "type" : "string",
        "enum" : ["Equal" , "Not equal"]
      },
      "name":{
        "type": "string"
      },
      "operator" : {
        "type" : "string",
        "enum" : ["Contains"]
      }
     }
  }
}

但我无法将每个键与操作员联系起来。我该怎么做?

【问题讨论】:

    标签: json object schema ajv


    【解决方案1】:

    这是使用“JSON Extended Structural Schema”语言表达需求的一种方式(据我所知),JESS:

    [
        ["&",
         {"comment": "https://stackoverflow.com/questions/57291339/validate-each-object-key-in-the-object-array-with-json-schema-in-ajv",
          "::<=":  {
                     "age": "number",
                     "operator": "string",
                     "name": "string",
                     "date": "number"
          }
         },
         { "comment": "age field can get only Equal and Not equal operator values",
           "ifcond": { "has": "age"},
           "then":   ["&", {"forall": ".[operator]", "enumeration": ["Equal", "Not equal"]}]
         },
         { "comment": "name should be used with Contains operator",
           "ifcond": { "forall": ".[operator]", "equal": "Contains" },
           "then":   ["&", {"has": "name" } ]
         }
        ]
    ]
    
    

    说明

    JESS 模式是 JSON 文本的集合。在这里,一个 JSON 文档就足够了,如上所示。

    外部方括号表示目标 JSON 实体必须是 JSON 数组的要求。

    “&”表示后面是约束的结合。这里有三个顶级约束,每个都有一个“评论”字段来指示正在发生的事情。简而言之:

    1. 第一个顶级约束表示要求数组的组件必须包含使用具有所示类型约束的任何指定键形成的对象。

    2. 第二个顶级约束表示“年龄字段只能获取Equal和Not equal运算符值”的条件。

    3. 第三个表示如果 .operator 的值为对象中的“包含”,则该对象必须具有“名称”键(其类型已在 (1.) )。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 2017-11-08
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2021-05-18
      • 2020-07-28
      相关资源
      最近更新 更多