jac*_*ack 3 arrays shell json loops node.js
我有多个json文件,它们只是想从中合并特定对象,然后将其保存到新的json文件中:例如:
one.json
two.json
...
Run Code Online (Sandbox Code Playgroud)
每个json文件都是这样的:
一个.json
{
"passed": 1,
"fixtures": [
{
"name": "Getting Started one",
"path": "testOne.ts"
}
]
}
Run Code Online (Sandbox Code Playgroud)
two.json
{
"passed": 1,
"fixtures": [
{
"name": "Getting Started two",
"path": "testTwo.ts"
}
]
}
Run Code Online (Sandbox Code Playgroud)
所以我的最终json文件应该是这样的:
final.json
{
"passed": 2,
"fixtures": [{
"name": "Getting Started one",
"path": "testOne.ts"
},
{
"name": "Getting Started two",
"path": "testTwo.ts"
}
]
}
Run Code Online (Sandbox Code Playgroud)
您知道这样合并的简单方法是什么吗?
节点:json文件不仅是两个,而且很多,因此最好找到每个扩展名为json的文件。最好在shell脚本或node.js中执行此操作。
谢谢。
Can do something like this using Promise:
const fs = require('fs');
const data = {
"passed": 0,
"fixtures": []
};
const dir = `${__dirname}/data/`;
fs.readdir(dir, (err, files) => {
return new Promise((resolve, reject) => {
if (err) reject(err);
files.forEach(file => {
console.log(file);
let content = require(`${dir}${file}`);
data['passed'] += content.passed;
data['fixtures'] = data['fixtures'].concat(content['fixtures']);
});
resolve(data);
}).then(data => {
fs.writeFileSync('./final.json',JSON.stringify(data));
});
})
Run Code Online (Sandbox Code Playgroud)
Using Async/Await it can done like this:
const fs = require('fs');
const path = require('path');
const dir = path.join(__dirname, 'data');
let finalContent = { "fixtures": [], "passed": 0 };
const read_directory = async dir =>
fs.readdirSync(dir).reduce((finalContent, file) => {
filePath = path.join(dir, file);
console.log(filePath);
let content = require(filePath);
finalContent.passed += content.passed;
finalContent.fixtures = finalContent.fixtures.concat(content.fixtures);
return finalContent;
}, { "passed": 0, "fixtures": [] });
read_directory(dir).then(data => {
fs.writeFileSync('./final.json', JSON.stringify(data));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3881 次 |
| 最近记录: |