You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js批量删除JSON文件中指定的属性条目

Node.js 批量删除JSON指定属性条目实现方案

你可以直接使用Node.js原生模块完成需求,无需引入第三方依赖,核心逻辑是读取JSON文件后通过数组filter方法过滤掉trait_type为body和eyes的条目,再写回文件即可。

完整实现代码

const fs = require('fs/promises');
const path = require('path');

// 自定义配置项
const CONFIG = {
  // 替换为你存放待处理JSON文件的文件夹路径
  targetDir: './json-files',
  // 需要删除的trait_type值列表
  invalidTraits: ['body', 'eyes']
}

async function processJsonFiles() {
  try {
    // 读取目标文件夹下的所有JSON文件
    const allFiles = await fs.readdir(CONFIG.targetDir);
    const jsonFileList = allFiles.filter(file => path.extname(file).toLowerCase() === '.json');

    for (const jsonFile of jsonFileList) {
      const fullPath = path.join(CONFIG.targetDir, jsonFile);
      // 读取并解析JSON内容
      const rawContent = await fs.readFile(fullPath, 'utf8');
      const jsonData = JSON.parse(rawContent);

      // 过滤attributes数组
      if (Array.isArray(jsonData.attributes)) {
        jsonData.attributes = jsonData.attributes.filter(attr => {
          return !CONFIG.invalidTraits.includes(attr.trait_type);
        });
      }

      // 格式化后写回原文件
      await fs.writeFile(fullPath, JSON.stringify(jsonData, null, 2), 'utf8');
      console.log(`已处理:${jsonFile}`);
    }
    console.log('全部文件处理完成');
  } catch (error) {
    console.error('处理过程出错:', error);
  }
}

processJsonFiles();

使用注意事项

  • 处理前请先备份原JSON文件,避免误操作导致数据丢失
  • 如果仅需处理单个JSON文件,可删除文件夹遍历逻辑,直接指定单个文件路径读取即可
  • 代码中JSON.stringify的第三个参数为2,表示输出的JSON缩进2个空格,你可以根据自己的格式需求调整

内容的提问来源于stack exchange,提问作者Firat Yildirim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:24:06