Ajv:使用动态键验证 JSON

4

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

今天我想使用以下结构:

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

我的键是动态的,因为它们是ids。您知道如何使用ajv进行验证吗?
附注:作为替代方案,我当然可以使用此结构:
const dataStructure = {
    mobiles: [{
        id: xxx1234,
        mobile: "ios"
    }, {
        id: yyy89B,
        mobile: "android"
    }]
};

那么我就必须在数组中循环查找我想要的id。所有我的查询都会变得更加复杂,这让我烦恼。

谢谢你的帮助!

1个回答

6
以下示例可能对您有所帮助。
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); 

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


你好@IftekharDani,谢谢你的提议!它确实验证了备选方案的架构。你知道如何验证第一个数据结构吗? - Vivien Adnot
在这个对象 xxx1234: { mobile: "ios" }, 中,您需要验证 xxx1234 吗? - IftekharDani
或者只验证 { mobile: "ios" } - IftekharDani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接