I think this could be a possible solution:
const fs = require("fs");
let files = fs.readdirSync("library");
function mergeJson() {
const output = files.reduce((acum, current) => {
data = fs.readFileSync(`./library/${current}`);
const newData = JSON.parse(data);
return {
...acum,
...newData,
};
}, {});
if (output) {
fs.writeFileSync(`combine.json`, JSON.stringify(output), { flag: "a" });
}
}
mergeJson();
Answer from Franco Aguilera on Stack OverflowVideos
» npm install json-merger
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(`
{file}`);
data['passed'] += content.passed;
data['fixtures'] = data['fixtures'].concat(content['fixtures']);
});
resolve(data);
}).then(data => {
fs.writeFileSync('./final.json',JSON.stringify(data));
});
})
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));
});
First, deserialize the JSON into the object and put all the objects into a list and then serialize the list object to JSON.
» npm install gulp-merge-json
Use Deferreds:
$.when(
this.$http.get('../../app/shared/labels/default.de.json'),
this.$http.get('../../app/shared/labels/success.de.json')
).done( function( a1, a2 ) {
json = $.extend({}, a1, a2);
});
Promises are resolved later. You are trying to merge jsons when they are not received yet. Try like below:
var mergedResult=null;
$.when(
this.$http.get('../../app/shared/labels/default.de.json'),
this.$http.get('../../app/shared/labels/success.de.json') )
.done(function( json1, json2 ) {
mergedResult = $.extend({}, json1, json2);
});
Based on your description in the comments, you'd simply do an array concat():
var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
console.log(jsonArray1)
// [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}, {'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
The actual way is using JS Object.assign.
Object.assign(target, ...sources)
MDN Link
There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.
Obj = {...sourceObj1, ...sourceObj2}
Either as individual attributes or as an array
{
"data1":{stuff for data1},
"data2":{stuff for data2},
"data3":{stuff for data3}
}
or
{"response":[
{stuff for data1},
{stuff for data2},
{stuff for data3}]}
If you really want to reduce the number of HTTP requests from the client, one possible way is like this:
- Build a server side proxy that get JSon files from the third party data sources
- Merge your 3 JSon files in one single JSon file
- Make a single $.getJSON() call to your single JSon from client
To merge Json files, look at this post.