Search code examples
javascriptjsongruntjsgrunt-contrib-concat

Grunt concat multiple JSON files


I have multiple JSON files, each located in different paths. Now I'm trying to concat all files with "grunt-concat-json".

The source JSON files are looking like this:

ExampleA.json

[ {
     "configPath": "Example A"
} ]

ExampleB.json

[ {
   "configPath": "Example B"
} ]

How can I configure my GRUNT Task to get following result JSON File:

[
   {
       "configPath": "Example A"
   },
   {
       "configPath": "Example B"
   } ]

I've tried with this config:

concat: {
 json:
     {
        src: [
                'pathA/ExampleA.json',
                'pathB/ExampleB.json
            ],
        dest: 'pathX/Merged.json',
            options: {
                separator: ','
            }
        }
    },

With this setting I get following result:

[
    {
       "configPath": "Example A"
    }
],
[
   {
       "configPath": "Example B"
   }
] 

but my result JSON should only have ONE array, which I can loop through in my code like

configPaths.forEach(configPath) {  ...  }

Solution

  • Here is a very basic zero-validation implementation that should be just enough to get you started.

    grunt.registerMultiTask('concatArrays', 'concatArrays', function() {
        this.files.forEach(function(_set) {
            var combined = [];
            _set.src.forEach(function(_file) {
                combined = combined.concat(JSON.parse(grunt.file.read(_file)));
            });
            grunt.file.write(_set.dest, JSON.stringify(combined));
        });
    });
    

    You can configure filesets like:

    concatArrays: {
        local: {
            files: [{
                src: ['a.json', 'b.json'],
                dest: 'combined.json'
            }],
        }
    }