多个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文件应该有一个列row10,其中包含需要检查的JSON文件的名称。运行上述脚本即可按照Excel中文件顺序输出结果

bash 复制代码
node parentDirectory/JSONChecker/JSONChecker.js
相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万3 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
譕痕3 天前
JSONObject与JSONArray封装数据格式区别
java·json
A黄俊辉A3 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄3 天前
JavaScript 隐式全局变量解析
javascript
汉堡大王95273 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端