【问题标题】:Ajv: validate json with dynamic keysAjv:使用动态键验证 json
【发布时间】:2019-04-03 06:37:07
【问题描述】:

在插入/更新我的数据库之前,我使用 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。 我所有的查询都会变得更加复杂,这让我很困扰。

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js json ajv


    【解决方案1】:

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

    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 谢谢你的提议!它确实验证了替代解决方案的架构。你知道如何验证第一个数据结构吗?
    • 这个对象xxx1234: { mobile: "ios" },你需要验证xxx1234吗?
    • 或仅验证{ mobile: "ios" }
    猜你喜欢
    • 2016-08-23
    • 2017-04-29
    • 1970-01-01
    • 2017-08-06
    • 2019-10-25
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    相关资源
    最近更新 更多