javascript - javascript - 验证嵌套的 json 对象
问题描述
我有以下 json 模式。
const myJson = {
"type": "typeName"
"firstName": "Steven",
"lastName": "Smith",
"address": {
"primary": {
"city": "abc",
"street": {
"name": {
"subName": "someName"
}
}
}
}
}
而且我想遍历每个属性以在此 json 上进行所需的验证,到目前为止,如果 json 中的属性没有嵌套,我有以下代码可以工作。
let errors = [];
const typeName = ['firstName', 'lastName'],
const typeAttr = Object.keys(myJson);
typeName.forEach(attr => {
if (!typeAttr.includes(attr)) {
errors.push(`Missing field: ${attr}`);
}
});
如何添加嵌套的 json 属性,如,primary
并验证我的操作方式。city
street
解决方案
我会做这样的事情。此方法给出数据是否具有所有提供的键,即,将返回true
或false
let obj = {"type":"typeName","firstName":"Steven","lastName":"Smith","address":{"primary":{"city":"abc","street":{"name":{"subName":"someName"}}}}};
const typeName = ['firstName', 'lastName', 'address', 'address.primary', 'address.primary.city', 'address.primary.street'];
const validate = (data, types) => {
return types.every(type => {
// Split the keys using `.`
const keys = type.split('.');
// Check if the length is more than 1,
// if yes, then we need to check deeply
if (keys.length > 1) {
let datum = {
...data
};
// Check through all the keys found using split
for (let key of keys) {
// if any key is not found or falsy then return false
if (!datum[key]) {
return false;
}
datum = datum[key];
}
return true;
} else {
// if the length of the keys is not more than 1 then it means
// the key is at the top level and return the value as boolean
return !!data[type]
}
})
}
console.log(validate(obj, typeName));
console.log(validate(obj, ['firstName', 'lastName', 'address', 'address.primary', 'address.primary.zip']));
下面的方法将返回提供的数据中不存在的键
const validate = (data, types) => {
let errors = [];
types.forEach(type => {
const keys = type.split('.');
let datum = {
...data
};
// Loop through the keys
for (let [index, key] of keys.entries()) {
// Check if the key is not available in the data
// then push the corresponding key to the errors array
// and break the loop
if (!datum[key]) {
errors.push(keys.slice(0, index + 1).join('.'));
break;
}
datum = datum[key];
}
})
return errors;
}
const obj = {"type":"typeName","firstName":"Steven","lastName":"Smith","address":{"primary":{"city":"abc","street":{"name":{"subName":"someName"}}}}};
const typeName = ['firstName', 'lastName', 'address', 'address.primary', 'address.primary.city', 'address.primary.street'];
console.log(validate(obj, ['firstName', 'lastName']));
console.log(validate(obj, ['firstName', 'lastName', 'address', 'address.primary', 'address.primary.zip']));
console.log(validate(obj, [...typeName, 'test', 'address.primary.zip', 'address.test.zip']));
推荐阅读
- php - 如何正确转义嵌套在 CSV 列中的 JSON 对象中的字符串中的双引号?
- python - cam.release() 后网络摄像头灯仍然亮着
- scala - Scala 类型推理混乱:有还是没有?
- c++ - 在 C++08 中初始化对象以作为参数传递的首选语法是什么?
- javascript - React/D3:从孩子渲染图
- c# - 无法创建接口类型的实例
- html - 从 iframe 中的角度应用程序内部访问隐藏 div 的值
- here-api - 通过 REST API 查询链接
- swift - 全局命名空间的一致性如何满足协议要求?
- regex - 在其他空括号(包括)之间选择空格和换行符