首页 > 解决方案 > 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并验证我的操作方式。citystreet

标签: javascriptecmascript-6

解决方案


我会做这样的事情。此方法给出数据是否具有所有提供的键,即,将返回truefalse

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']));


推荐阅读