[英]JSON Schema extract the required fields
我需要從JSON-Schema + Data中獲取所需字段的列表。
目前,我們正在使用AJV在我們的表單中使用JSON Schema獲取錯誤消息,並且它運行良好。
我需要一種方法來獲取所有必需的字段(即使已填充),以便將這些字段標記為*為“required”。 必填字段可能會更改,具體取決於架構和數據組合。
還試圖通過黑客攻擊tv4來提取所需的字段但沒有成功。
請幫忙。
此類架構的示例:
{
"type": "object",
"required": [
"checkbox"
],
"properties": {
"checkbox": {
"type": "boolean"
},
"textbox": {
"type": "string"
}
},
"oneOf": [
{
"required": [
"textbox"
],
"properties": {
"checkbox": {
"enum": [
true
]
}
}
},
{
"properties": {
"checkbox": {
"enum": [
false
]
}
}
}
],
"additionalProperties": false
}
重讀你的問題是做你想做的最簡單的方法
樣品1
for(let prop in data) {
if(data.hasOwnProperty(prop) {
//set value to null, -1, or some other universally bad value
data[prop]...value = null;
}
}
樣本2
let result = tv4.validateMultiple(data, schema);
let required = result.errors;
我們解決了它:
分叉tv4(tv4 - 因為它很容易編輯):
https://github.com/mikila85/tv4
輸出“Requireds”數組。
我們迭代了每個必需的字段,清空它的數據並將數據+模式發送到AJV進行驗證(AJV而不是tv4,因為它在解析時速度更快)。
通過這樣做,我們可以分別知道給定數據所需的字段。
這些是我們提出的工作功能(不是最干凈但有助於理解)
function getAllRequiredFields() {
var allRequiredFields = tv4.validateMultiple($scope.formModel, $scope.formSchema).requireds;
allRequiredFields = allRequiredFields.filter(function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
});
return allRequiredFields;
}
function getRequiredFields() {
var t0 = performance.now();
//should be called every model change because of optimization in tv4 for the data+schema.
var allRequiredFields = getAllRequiredFields();
angular.forEach(allRequiredFields, function (requiredPath) {
var modelWithDeletedRequiredProperty = angular.copy($scope.formModel);
deleteValue(modelWithDeletedRequiredProperty, requiredPath);
if (!validateForm(modelWithDeletedRequiredProperty)) {
var requiredError = getErrorObjectsArray(validateForm.errors).find(function (error) {
return error.path === requiredPath;
});
if (requiredError) {
localValidation[requiredError.inputName] = localValidation[requiredError.inputName] || {};
localValidation[requiredError.inputName].isRequired = true;
requiredFieldsPath.push(requiredError.inputName);
}
}
});
var t1 = performance.now();
console.log("form checking took " + (t1 - t0) + " milliseconds.");
}
這個函數遞歸地抓取模式索引,所以也許你可以調整一下
// https://github.com/pubkey/rxdb/blob/master/src/rx-schema.js
export function getIndexes(jsonID, prePath = '') {
let indexes = [];
Object.entries(jsonID).forEach(entry => {
const key = entry[0];
const obj = entry[1];
const path = key === 'properties' ? prePath : util.trimDots(prePath + '.' + key);
if (obj.index)
indexes.push([path]);
if (typeof obj === 'object' && !Array.isArray(obj)) {
const add = getIndexes(obj, path);
indexes = indexes.concat(add);
}
});
if (prePath === '') {
const addCompound = jsonID.compoundIndexes || [];
indexes = indexes.concat(addCompound);
}
indexes = indexes
.filter((elem, pos, arr) => arr.indexOf(elem) === pos); // unique;
return indexes;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.