我可以使用 grunt 在 json 文件中设置 属性 值吗?

Can I use grunt to set a property value in a json file?

仍在学习 g运行t 的诀窍,找不到解决方案。 我有一个配置文件,比如 config.json 和一些数据。

当我 运行 一个特定的 g运行t 任务时,我想在 config.json 文件中增加一个值。我已经能够找到很多关于如何读取文件的信息,但到目前为止还没有关于更改值的信息。

谢谢。

您可以使用 https://github.com/eruizdechavez/grunt-string-replace 替换字符串并保存文件

'string-replace': {
  dist: {
    files: {
      'dest/': 'src/**',
      'prod/': ['src/*.js', 'src/*.css'],
    },
    options: {
      replacements: [{
        pattern: /\/(asdf|qwer)\//ig,
        replacement: '""'
      }, {
        pattern: ',',
        replacement: ';'
      }]
    }
  }
}

使用这个 grunt 插件,您可以用替换项替换正则表达式模式(或简单的字符串)

完成最终 json 的步骤是:

这里是一个使用 grunt 任务更新 package.json 文件版本的例子。 (从 0.0.0 到 1.0.0 再到 2.0.0);

module.exports = function(grunt) {
    grunt.registerTask('version', function(key, value) {
        var projectFile = "package.json";
        if (!grunt.file.exists(projectFile)) {
            grunt.log.error("file " + projectFile + " not found");
            return true; //return false to abort the execution
        }
        var project = grunt.file.readJSON(projectFile), //get file as json object
            currentVersion = project["version"].split('.');

        currentVersion[lastIndex] = Number(currentVersion[0]) + 1
        currentVersion = currentVersion.join('.');

        project["version"] = currentVersion;
        grunt.file.write(projectFile, JSON.stringify(project, null, 2));
    });
}

现在您可以通过写入

调用任务版本来递增文件
grunt version

或者您可以将其添加到您的生产过程中,例如:

module.exports = function(grunt) {
    grunt.registerTask('buildProd', [
      'version'
    ]);
};

我根据 giammangiato 的回答找到了解决方案。

我阅读了 JSON 文件,进行了更改,然后通过使用修改后的 JSON 编写一个新文件来替换整个文件,如下所示:

var mrJSON = grunt.file.readJSON('myDir/config.json');

    var mrNumber  = mrJSON.number;

    mrNumber++;


    grunt.file.write('myDir/config.json', JSON.stringify(mrJSON));