将JSON文件与grunt-contrib-concat结合使用

时间:2013-04-11 02:04:54

标签: javascript json concatenation gruntjs

我正在寻找将json文件合并到一个文件夹中的最佳方法。

使用HTML,CSS和JavaScript,这非常简单,因为您不需要分隔符或只需要一个;。 但是,使用JSON,我们需要更多东西才能使它成为有效的JSON对象。

一种方法是将文件与,连接起来并将所有内容包装在一个数组中。我想知道是否有更好/更简单的方法来做到这一点。

Gruntfile.js

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
        json: {
            src: ['src/**/*.json'],
            dest: 'dist/combined.json',
            options: {
              ...
            }
        }
    }
});

的src / file1.json

{
    "number": 1
}

的src / file2.json

{
    "number": 2
}

DIST / combined.json

这将是理想的结果:

{
    "numbers": [
        {
            "number": 1
        },
        {
            "number": 2
        }
    ]
}

3 个答案:

答案 0 :(得分:4)

您应该可以使用bannerfooter选项。

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
        json: {
            src: ['src/**/*.json'],
            dest: 'dist/combined.json',
            options: {
                // Added to the top of the file
                banner: '{"numbers": [',
                // Will be added at the end of the file
                footer: "]}",
                separator: ','
            }
        }
    }
});

答案 1 :(得分:1)

您可以使用grunt-merge-json

用法示例:

假设我们有以下类型的源JSON文件:

src/foo/foo-en.json:
{
    "foo": {
        "title": "The Foo",
        "name":  "A wonderful component"
    }
}
src/bar/bar-en.json:
{
    "bar": {
        "title": "The Bar",
        "name":  "An even more wonderful component"
    }
}

假设我们要生成以下目标JSON文件:

{
    "foo": {
        "title": "The Foo",
        "name":  "A wonderful component"
    },
    "bar": {
        "title": "The Bar",
        "name":  "An even more wonderful component"
    }
}

每个目标变体的单个文件

grunt.initConfig({
    "merge-json": {
        "en": {
            src: [ "src/**/*-en.json" ],
            dest: "www/en.json"
        },
        "de": {
            src: [ "src/**/*-de.json" ],
            dest: "www/de.json"
        }`enter code here`
    }
});

每个目标变体有多个文件

grunt.initConfig({
    "merge-json": {
        "i18n": {
            files: {
                "www/en.json": [ "src/**/*-en.json" ],
                "www/de.json": [ "src/**/*-de.json" ]
            }
        }
    }
});

答案 2 :(得分:1)

您应该使用专用的面向JSON的插件来处理它。不只是一个任意的字符串连接。

查看https://github.com/rse/grunt-merge-jsonhttps://github.com/shinnn/grunt-merge-data