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
Can this tool merge JSON arrays (not just objects)?
Will merging break my JSON formatting or encoding?
Can I use this for merging API response files or config files?
» 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
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.
You want the concat method.
var finalObj = json1.concat(json2);
Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.
What you seek is a simple javascript function known as .concat. Which would work like:
var finalObj = json1.concat(json2);
While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
}
});
}
})(jQuery);
And then recall it as desired like:
var finalObj = $.concat(json1, json2);
You can also use it for multiple array objects of this type with a like:
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
And if you really want it jQuery style and very short and sweet (aka minified)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
$(function() {
var json1 = [{id:1, name: 'xxx'}],
json2 = [{id:2, name: 'xyz'}],
json3 = [{id:3, name: 'xyy'}],
json4 = [{id:4, name: 'xzy'}],
json5 = [{id:5, name: 'zxy'}];
console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3));
console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3, json4, json5));
console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
console.log($.concat(json4, json1, json2, json5));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>
jsFiddle