admin管理员组

文章数量:1333177

I use ajv to validate JSON data model before inserting/updating my database.

Today I want to use this structure:

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

My keys are dynamic because they are ids. Do you know how to validate it with ajv ?

PS: as an alternative solution, i can of course use this structure:

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

Then I would have to loop on the array to find the ids I want. All my queries will bee more plex, it bothers me.

Thank you for your help !

I use ajv to validate JSON data model before inserting/updating my database.

Today I want to use this structure:

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

My keys are dynamic because they are ids. Do you know how to validate it with ajv ?

PS: as an alternative solution, i can of course use this structure:

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

Then I would have to loop on the array to find the ids I want. All my queries will bee more plex, it bothers me.

Thank you for your help !

Share Improve this question asked Oct 30, 2018 at 8:57 Vivien AdnotVivien Adnot 1,2574 gold badges17 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Below example may help you.

1.Validate dynamic key value

Update regex with your requirement.

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.pile(schema2);

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

2.Validate array of JSON with simple data types.

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.pile(schema);

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

You can add your validation as per requirement.

本文标签: javascriptAjv validate json with dynamic keysStack Overflow