将 json 文件对象拍平
demo.json
{
"a": {
"b": 123
},
"c": "abc"
}
期望将 demo.json 对象拍平
{
"a_b": 123,
"c": "abc"
}
源码示例
const fs = require('fs');
// 读取 JSON 文件
function readJSONFile(filename) {
try {
const data = fs.readFileSync(filename, 'utf8');
return JSON.parse(data);
} catch (err) {
console.error('Error reading JSON file:', err);
return null;
}
}
// 递归遍历 JSON 对象并展平
function flattenJSON(obj, parentKey = '') {
const flattenedObj = {};
for (let key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
// 递归展平子对象
const flatChild = flattenJSON(obj[key], `${parentKey}${parentKey && '_'}${key}`);
Object.assign(flattenedObj, flatChild);
} else {
// 将键添加到展平的对象中
const newKey = parentKey ? `${parentKey}_${key}` : key;
flattenedObj[newKey] = obj[key];
}
}
return flattenedObj;
}
// 写入展平后的 JSON 到文件
function writeJSONFile(filename, data) {
try {
fs.writeFileSync(filename, JSON.stringify(data, null, 4));
console.log(`Flattened JSON written to ${filename}`);
} catch (err) {
console.error('Error writing JSON file:', err);
}
}
// 主函数
function main(inputFile, outputFile) {
const jsonData = readJSONFile(inputFile);
if (!jsonData) return;
const flattenedJSON = flattenJSON(jsonData);
writeJSONFile(outputFile, flattenedJSON);
}
// 用法示例:node script.js input.json output.json
const args = process.argv.slice(2);
if (args.length !== 2) {
console.error('Usage: node script.js input.json output.json');
process.exit(1);
}
const inputFile = args[0];
const outputFile = args[1];
main(inputFile, outputFile);