4

I have multiple json files which just want to merge particular object from them and then save it into new json file: for example:

one.json
two.json
...

and each json file is like this:

one.json

{
  "passed": 1,
  "fixtures": [
    {
      "name": "Getting Started one",
      "path": "testOne.ts"
    }
  ]
}

two.json

{
  "passed": 1,
  "fixtures": [
    {
      "name": "Getting Started two",
      "path": "testTwo.ts"
    }
  ]
}

so my final json file should be like this:

final.json

{
    "passed": 2,
    "fixtures": [{
            "name": "Getting Started one",
            "path": "testOne.ts"
        },
        {
            "name": "Getting Started two",
            "path": "testTwo.ts"
        }
    ]
}

do you have an idea what is the simple way to merge like this.

node: json files is not just two but many so it is good to find every file which has a extension of json. it is good to do this in shell script or node.js.

thanks.

3 Answers 3

7

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));
    });
})

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));
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your great solution, i have revised the question, actually i have adding another object into each json which is not array, but number , and in a final json it should be the sum of all number, do have solution for this situation. thanks
Updated, have a look
0

First, deserialize the JSON into the object and put all the objects into a list and then serialize the list object to JSON.

Comments

-1

Actually, if you want to do it by node.js, you can use one of the node packages, that will make it for you very easy. For example, it's a good merge json package - https://www.npmjs.com/package/package-merge

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.