使用grunt-contrib-concat组合JSON文件

Combine JSON files with grunt-contrib-concat

本文关键字:文件 JSON 组合 grunt-contrib-concat 使用      更新时间:2023-09-26

我正在寻找在文件夹中组合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: ','
            }
        }
    }
});

你应该使用一个专门的和面向JSON的插件来处理。不只是一个任意的字符串concat。

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

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