I want to browse directories for json files and merge all json files into one json file per directory. My javascript skill is at beginner level.
The javascript code needs to run by calling it in the Terminal, not in the browser.
CodePudding user response:
you can make use of glob npm package to retrieve all json file paths in the directories.
glob : https://www.npmjs.com/package/glob
you can simply go with :
const glob = require("glob");
const fs = require('fs-extra');
async function processJsonData(){
let parentDirectoryPath = '<specify path here>';
let data = {};
let jsonFilePaths = glob.sync(`${parentDirectoryPath}/*/*.json`);
//this will return paths for all the json files
for (const jsonFilePath of jsonFilePaths) {
let content = await fs.readJsonSync(jsonFilePath);
Object.assign(data,content);
}
await fs.writeJson(<filePath>, data, {spaces: 2});
//here specify your file path
}
ps. I am a new contributor, might have misread the question.