合并两个具有相似属性的bower.json文件(合并两个具有相似属性的JSON文件)

时间:2015-05-22 14:51:19

标签: javascript json gruntjs bower

我想合并两个bower.json文件。一个是我的项目的本地,另一个是在不同的项目之间共享。我需要在运行bower install之前合并这两个文件。

请查看示例以了解我的要求:

本地bower.json

sed 's/PurchaseOrderNumber="/PurchaseOrderNumber="001/g'

并分享bower.json

{
    "name": "myLocalProject",
    "version": "0.0.1",
    "devDependencies": {
        "angular": "1.1.0"
    },
    "dependencies": {
       "components-font-awesome": "*"
    },
    "resolutions": {
        "angular": "1.3.15"
    }
}

和结果bower.json将替换本地bower.json

{
    "name": "sharedBowerFile",
    "version": "0.0.3",
    "devDependencies": {
        "angular": "1.3.15",
        "angular-resource": "1.3.15"
    },
    "dependencies": {

    },
    "resolutions": {
        "angular": "1.3.15"
    }
}

我将为合并创建一个Grunt任务,所以我需要在JavaScript中进行合并。

1 个答案:

答案 0 :(得分:0)

好的,我自己写了这个函数:

var mergeJSON = function (local, shared) {
    var check = true;
    for(var i in shared ) {
        if(typeof(shared[i]) == 'object') {
            for(var j in shared[i]) {
                check =true;
                for (var z in local[i]) {
                    if(j == z){
                        check = false;
                            if( cmp(shared[i][j], local[i][j])>0 ) {
                            //For upgrading the version of dependencies from shared to local
                            grunt.log.writeln("Updating local " + j + " from " + local[i][j] + " to >" + shared[i][j]);
                            local[i][j] = shared[i][j];
                            }else if(cmp(shared[i][j], local[i][j])<0){
                                grunt.log.writeln(j + " in shared bower.json " + " is " + shared[i][j] + " and older than local version " + local[i][j]);

                            }
                    }
                }
                if(check){
                    //add the dependency if does not exist in local
                    local[i][j] = shared[i][j];
                    grunt.log.writeln("Added dependency: " + j + ": " + local[i][j] );
                }
            }
        }
    }
    return JSON.stringify(local,null,4);
};

和我的Grunt任务:

 grunt.task.registerTask('merge','A task to merge local and shared bower.json file', function(){

            var shared = grunt.file.readJSON("/path/to/sharedJSON");
            var local = grunt.file.readJSON("bower.json");
            grunt.file.write('bower.json',mergeJSON(local,shared));
    });

运行:

$ grunt merge