AJV:使用动态密钥验证JSON

薇薇安·阿姆特

我在插入/更新数据库之前使用ajv来验证JSON数据模型。

今天,我要使用以下结构:

const dataStructure = {
    xxx1234: { mobile: "ios" },
    yyy89B: { mobile: "android" }
};

我的键是动态的,因为它们是id。你知道如何用ajv进行验证吗?

PS:作为一种替代解决方案,我当然可以使用以下结构:

const dataStructure = {
    mobiles: [{
        id: xxx1234,
        mobile: "ios"
    }, {
        id: yyy89B,
        mobile: "android"
    }]
};

然后,我将不得不在数组上循环查找所需的ID。我所有的查询都会变得更加复杂,这困扰着我。

谢谢您的帮助 !

IftekharDani

以下示例可能会对您有所帮助。

1.验证动态键值

根据您的要求更新正则表达式。

const dataStructure = {
    11: { mobile: "android" },
    86: { mobile: "android" }
};
var schema2 = {
     "type": "object",
     "patternProperties": {
    "^[0-9]{2,6}$": { //allow key only `integer` and length between 2 to 6
        "type": "object" 
        }
     },
     "additionalProperties": false
};

var validate = ajv.compile(schema2);

console.log(validate(dataStructure)); // true
console.log(dataStructure); 

2.使用简单的数据类型验证JSON数组。

var schema = {
  "properties": {
    "mobiles": {
      "type": "array", "items": {
        "type": "object", "properties": {
          "id": { "type": "string" },
          "mobile": { "type": "string" }
        }
      }
    }
  }
};
const data = {
  mobiles: [{
    id: 'xxx1234',
    mobile: "ios"
  }]
};

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); 

您可以根据要求添加验证。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章