如何使用Object.assign批量转换指定结构的JSON文件
实现方案
核心转换逻辑
你要做的转换本质是把properties数组内的所有单键值对象合并为一个顶级对象,直接用Object.assign即可实现,核心代码如下:
// 假设original是读取原始JSON后解析得到的对象 const converted = Object.assign({}, ...original.properties);
如果需要输出的键按字母升序排列(和你给出的目标结构顺序一致),可以追加排序逻辑:
const sortedConverted = Object.fromEntries( Object.entries(converted).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)) );
批量处理JSON文件的完整实现(Node.js环境)
你可以用Node.js内置的fs、path模块完成批量文件处理,代码示例如下:
const fs = require('fs/promises'); const path = require('path'); // 配置项:修改为你存放JSON文件的目录路径 const JSON_DIR = './your-json-files-path'; async function batchConvertJson() { // 读取目录下所有文件 const files = await fs.readdir(JSON_DIR); // 筛选出后缀为.json的文件 const jsonFiles = files.filter(file => path.extname(file).toLowerCase() === '.json'); for (const file of jsonFiles) { const filePath = path.join(JSON_DIR, file); try { // 读取并解析原始JSON const rawContent = await fs.readFile(filePath, 'utf8'); const originalData = JSON.parse(rawContent); // 转换结构 const convertedData = Object.assign({}, ...originalData.properties); // 可选:开启下面的注释让键按字母排序 // const sortedData = Object.fromEntries(Object.entries(convertedData).sort(([a],[b])=>a.localeCompare(b))) // 写回文件,2是格式化缩进的空格数 await fs.writeFile(filePath, JSON.stringify(convertedData, null, 2), 'utf8'); console.log(`处理完成:${file}`); } catch (err) { console.error(`处理文件${file}失败:`, err.message); } } } batchConvertJson();
使用步骤
- 把上面的代码保存为
convert.js - 修改代码里的
JSON_DIR为你存放待处理JSON文件的实际目录路径 - 在代码所在目录执行
node convert.js即可完成批量处理
注意:如果担心修改原文件出错,可以先备份所有原始JSON文件,或者把写文件的路径改为新的输出目录,避免数据丢失。
内容的提问来源于stack exchange,提问作者Francis-William Rhéaume
相关产品推荐
相关产品推荐

