多个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
相关推荐
钛态3 分钟前
Flutter 三方库 react 泛前端核心范式框架鸿蒙原生层生态级双向超能适配:跨时空重塑响应式单向数据流拓扑与高度精密生命周期树引擎解耦视图渲染控制中枢(适配鸿蒙 HarmonyOS ohos)
前端·flutter·react.js
全栈前端老曹4 分钟前
【前端地图】地图开发基础概念——地图服务类型(矢量图、卫星图、地形图)、WGS84 / GCJ-02 / BD09 坐标系、地图 SDK 简介
前端·javascript·地图·wgs84·gcj-02·bd09·地图sdk
只与明月听5 分钟前
RAG深入学习之向量数据库
前端·人工智能·python
吕不说27 分钟前
AI 面试总挂?可能是表达出了问题:三层表达法 + STAR 进阶框架
前端
社恐的下水道蟑螂1 小时前
LangChain 进阶实战:从玩具 Demo 到生产级 AI 应用(JS/TS 全栈版)
前端·langchain·openai
Fairy要carry1 小时前
项目01-手搓Agent之loop
前端·javascript·python
亲亲小宝宝鸭1 小时前
Ctrl ACV工程师的提效之路:删掉项目中的冗余
前端
kyriewen1 小时前
DOM树与节点操作:用JS给网页“动手术”
前端·javascript·面试
米饭同学i1 小时前
基于腾讯云COS的小程序素材上传功能实现
前端·javascript·react.js
cxxcode1 小时前
前端性能指标接入 Prometheus 技术方案
前端