Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当文件将JSON对象分配给变量时,grunt如何提取JSON对象_Javascript_Json_Gruntjs - Fatal编程技术网

Javascript 当文件将JSON对象分配给变量时,grunt如何提取JSON对象

Javascript 当文件将JSON对象分配给变量时,grunt如何提取JSON对象,javascript,json,gruntjs,Javascript,Json,Gruntjs,我试图干净地处理JSON对象,但JSON被分配给如下变量: var test = { "foo" : "bar" }; { "foo" : "bar" } var jsonfile = grunt.file.readJSON(source) 我可以使用这样的文件结构: var test = { "foo" : "bar" }; { "foo" : "bar" } var jsonfile = grunt.file.readJSON(source) 然后像这样获取JSON: var t

我试图干净地处理JSON对象,但JSON被分配给如下变量:

var test = { "foo" : "bar" };
{ "foo" : "bar" }
var jsonfile = grunt.file.readJSON(source)
我可以使用这样的文件结构:

var test = { "foo" : "bar" };
{ "foo" : "bar" }
var jsonfile = grunt.file.readJSON(source)
然后像这样获取JSON:

var test = { "foo" : "bar" };
{ "foo" : "bar" }
var jsonfile = grunt.file.readJSON(source)

但是我需要将此过程自动化并保留当前的文件结构。

问题是我无法找到将javascript文件包含到grunt任务中的方法。因此,我所做的是将文件作为文本字符串读取

然后使用regex删除了表示变量赋值的字符串部分。最后,我可以将字符串解析为对象

  var test = grunt.file.read(source),
  re = new RegExp('var?.test?.=|;','gi'),
  test = JSON.parse(test.replace(re, ""));

FelixKing的解决方案实现了:

//somefile.js
var someJSONObject = {
    SOME_KEY: "VALUE";
};

module.exports = someJSONObject;

//Gruntfile.js
var json = require('somefile');
console.log(json.SOME_KEY); //logs "VALUE"

module.exports = function(grunt) {
  //...rest of grunt file
}
比使用正则表达式从原始字符串中解析“var=”更易于维护(也更灵活)。您不再局限于JSON,而是任何JavaScript

为了避免您担心将JS文件用于多种用途(因此当它不在节点环境中时,
somefile.JS
中可能不会定义
module
),您可以执行以下操作:

    //somefile.js
    var someJSONObject = {
        SOME_KEY: "VALUE";
    };

    //CommonJS export syntax
    //don't do anything if module.exports is not in scope
    if ( typeof module === "object" && typeof module.exports === "object" ) {
        module.exports = someJSONObject;
    }

嗯,
var-test={“foo”:“bar”}
不是JSON,而是JavaScript。我不确定你想要达到什么。我试着把对象读到我的自定义咕噜任务中。当我删除变量赋值时,它与Grun.Fiel.ReordJSON兼容,所以我认为这里的语法非常接近。我只想在对象有变量赋值时使导入工作,而不是手动删除变量赋值。似乎
var jsonfile=grunt.file.readJSON(source)
就是这样做的。编辑:那么您不想手动编辑文件的问题是什么?你可以编写一个一次性脚本来编辑你的文件。你可以
要求
任何你喜欢的文件,只要它能导出一些东西。Grunt只是一个在节点上运行的库。你可以做Node能做的任何事情。Felix King有最好的解决方案——确保你的JS文件导出一些东西,然后
require
将你的JS文件放在grunt文件的顶部,就像你在
require
'd所有其他grunt插件一样。当我尝试时,它不起作用。然而,这确实起到了作用。我同意这看起来更易于维护,我不知道我做了什么不同,但当我尝试这样做时,我分配给'someJSONObject'的变量只有null。@JackShultz-我的错,grunfile.js中的行应该是:
require('somefile')