javascriptjsonmergegruntjsgruntfile

Dynamic merge of JSON files in Gruntfile.js


In my gruntfile.js I'm using this plugin `grunt.loadNpmTasks('grunt-json-merge'); and I'm trying to merge two JSON files using this code:

    json_merge: {
        files: {
            files: { 'dest/resources/locales/merged.json':
                function () {
                    var includedScripts = [];
                                    includedScripts.push(project_x+'/locales/locale-fr.json');
                                    includedScripts.push(project_y+'/locales/locale-fr.json');
                    return includedScripts;

}
            },
        },
    }

I get Warning: pattern.indexOf is not a function Use --force to continue.

NB: I need to use a function to define the input values as it contains some variables and maybe I will need to integrate a for loop later.

The used library is this one https://github.com/ramiel/grunt-json-merge


Solution

  • The problem is that the value of an entry in the files object should be an array, but because you haven't called the function, only declared it, the value is a function.

    This should work:

    json_merge: {
        files: {
            files: { 'dest/resources/locales/merged.json':
                (function () {
                    var includedScripts = [];
                    includedScripts.push(project_x+'/locales/locale-fr.json');
                    includedScripts.push(project_y+'/locales/locale-fr.json');
                    return includedScripts;
                })() // call the function here to return the array
            },
        }
    }
    

    But you might also find it more comfortable to extract the function, give it a name, and then invoke it by name in the task:

    function getJSONFilesToMerge () {
        var includedScripts = [];
        includedScripts.push(project_x+'/locales/locale-fr.json');
        includedScripts.push(project_y+'/locales/locale-fr.json');
        return includedScripts;
    }
    
    // .....
    
    json_merge: {
        files: {
            files: { 
                'dest/resources/locales/merged.json': getJSONFilesToMerge()
            },
        }
    }