多个JSON文件中目标Key值检索

摘要:工作中需要将Excel中的文件名,与JSON文件逐个匹配,并查找其中目标key的值是否满足条件,尝试写了个JS脚本实现下...

1. 安装xlsx库

首先,需要安装xlsx库,允许用户在Node.js和浏览器环境中读写Excel文件。安装步骤简单

bash 复制代码
npm install xlsx

2. 创建脚本逐步实现功能

2.1 从Excel文件读取文件名并与JSON文件匹配

由于Excel中文件名称不完整,需要处理后,才能与JSON文件名称正确匹配

javascript 复制代码
// 从Excel文件读取文件名模式
async function getFileNamesFromExcel(excelFilePath) {
  // 读取Excel文件
  const workbook = XLSX.readFile(excelFilePath);
  // 获取第一个工作表
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  // 将工作表转换为JSON对象数组
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
  
  // 提取文件名列的值作为文件名模式数组
  const patterns = data.map(row => {
    return '前缀'+row[10]+ '.json';
  });
  return patterns;
}
2.2 读取JSON文件检查是否满足条件

按照Excel中匹配后的文件名,这个查找JSON文件,并判断是否满足条件

javascript 复制代码
// 读取并检查JSON文件
async function checkSpecifiedJsonFiles(fileNamesFromExcel, configsDir) {
  for (const fileNameFromExcel of fileNamesFromExcel) {
    const jsonFileName = fileNameFromExcel; //
    const filePath = path.join(configsDir, jsonFileName);

    try {
      // 读取文件
      const content = await fs.readFile(filePath, 'utf8');
      const config = JSON.parse(content);

      // 这里定义需求:检查 "targetKey1" 和 "targetKey2" 字段
      const targetKey1 = config.targetKey1;
      const targetKey2 = config.targetKey2;

      if (targetKey1 === true || targetKey1 === true) {
        console.log(`文件 ${jsonFileName} 不满足需求。`);
      } else {
        console.log(`文件 ${jsonFileName} 满足需求。`);
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        // 文件不存在
        console.log(`文件 ${jsonFileName} 不存在。`);
      } else {
        // 其他错误
        console.error(`处理文件 ${jsonFileName} 时发生错误:`, error);
      }
    }
  }
}

// 主函数
async function main() {
  try {
    const fileNames = await getFileNamesFromExcel(excelFilePath);
    await checkSpecifiedJsonFiles(fileNames, configsDir);
  } catch (error) {
    console.error('发生错误:', error);
  }
}

完整脚本:

javascript 复制代码
const fs = require('fs').promises;
const path = require('path');
const XLSX = require('xlsx');

// 假设Excel文件名为fileNames.xlsx, 并且JSONChecker和JSONDirector位于同一目录下
const excelFilePath = '/Users/JSONChecker/fileNames.xlsx';
const configsDir = '/Users/JSONDirectory';  // JSON配置文件的目录(绝对路径)

// 从Excel文件读取文件名模式
async function getFileNamesFromExcel(excelFilePath) {
  // 读取Excel文件
  const workbook = XLSX.readFile(excelFilePath);
  // 获取第一个工作表
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  // 将工作表转换为JSON对象数组
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
  
  // 提取row[10]列的值作为文件名模式数组
  const patterns = data.map(row => {
    return '前缀'+row[10]+ '.json';
  });
  return patterns;
}

// 读取并检查JSON文件
async function checkSpecifiedJsonFiles(fileNamesFromExcel, configsDir) {
  for (const fileNameFromExcel of fileNamesFromExcel) {
    const jsonFileName = fileNameFromExcel; //
    const filePath = path.join(configsDir, jsonFileName);

    try {
      // 读取文件
      const content = await fs.readFile(filePath, 'utf8');
      const config = JSON.parse(content);

      // 这里定义需求:检查 "targetKey1" 和 "targetKey2" 字段
      const targetKey1 = config.targetKey1;
      const targetKey2 = config.targetKey2;

      if (targetKey1 === true || targetKey1 === true) {
        console.log(`文件 ${jsonFileName} 不满足需求。`);
      } else {
        console.log(`文件 ${jsonFileName} 满足需求。`);
      }
    } catch (error) {
      if (error.code === 'ENOENT') {
        // 文件不存在
        console.log(`文件 ${jsonFileName} 不存在。`);
      } else {
        // 其他错误
        console.error(`处理文件 ${jsonFileName} 时发生错误:`, error);
      }
    }
  }
}

// 主函数
async function main() {
  try {
    const fileNames = await getFileNamesFromExcel(excelFilePath);
    await checkSpecifiedJsonFiles(fileNames, configsDir);
  } catch (error) {
    console.error('发生错误:', error);
  }
}

// 执行主函数
main();

3. 总结

将Excel文件保存为fileNames.xlsx,并确保它位于脚本所在目录下。Excel文件应该有一个列row[10],其中包含需要检查的JSON文件的名称。运行上述脚本即可按照Excel中文件顺序输出结果

bash 复制代码
node parentDirectory/JSONChecker/JSONChecker.js
相关推荐
tERS ERTS1 分钟前
头歌答案--爬虫实战
java·前端·爬虫
当时只道寻常9 分钟前
Vue3 集成 NProgress 进度条:从入门到精通
前端·vue.js
kyriewen10 分钟前
React性能优化:从“卡成狗”到“丝般顺滑”的5个秘诀
前端·react.js·性能优化
米丘10 分钟前
Vue 3.x 单文件组件(SFC)模板编译过程解析
前端·vue.js·编译原理
helloweilei12 分钟前
Web Streams 简介
前端·javascript
悟空瞎说12 分钟前
Flutter热更新 Shorebird CodePush 原理、实现细节及费用说明
前端·flutter
didadida26213 分钟前
从“不存在”的重复请求,聊到 Web 存储的深坑
前端
xiaominlaopodaren14 分钟前
Three.js 渲染原理-透明渲染为什么这么难
前端
米丘15 分钟前
vue3.x 内置指令有哪些?
前端·vue.js