繁体   English   中英

结合JSON文件与grunt-contrib-concat

[英]Combine JSON files with grunt-contrib-concat

我正在寻找在文件夹中合并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
        }
    ]
}

您应该能够使用标题页脚选项。

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: ','
            }
        }
    }
});

您可以为此使用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" ]
            }
        }
    }
});

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM