-1

In my project I have two Json files.

1) File1.json

{
  "abc" : 123
}

2) File2.json

import File1.json

{
  "xyz": 567
}

I need a way in javascript or angular js, which would help me achieve a file

File3.json whose content will be something like this

{
  "abc" : 123
},
{
  "xyz": 567
}
Gilles Heinesch
  • 2,889
  • 1
  • 22
  • 43

1 Answers1

0

You could use Node and FileSystem

You will need to change you files contents to:

{
    "array": [
        {
           "abc": 123
        }
    ]
}

And

{
   "array": [
      {
          "xyz": 567
      }
   ]
}

Then you can do this:

const fs = require('fs'); // Require Filesystem
let files = ['/File1.json', '/File2.json']; // The files you want to merge
let newData = { 'array': [] }; // The new data object. 

files.map( ( file ) => { // Loop the files
    fs.readFile( file, function read(err, data) { // Read file and pass data and the response
        if (err) { // Handle error
            throw err;
        }

        let parsedJson = JSON.parse(data) // Turn data into JSON

        parsedJson.array.map( ( object ) => { // Loop the array of objects.
            newData.array.push(object); // Push the object into the new structure.         
        });
    });
})

fs.writeFileSync('/File3.json', newData); // Write the new file.

I didn't actually run this but this should work.

Also i would suggest you use a Database instead of handling data in JSON files. Checkout Mongo DB it does this all for you :)

Nicolay Hekkens
  • 530
  • 5
  • 18