JavaScript - 使用方法将对象保存为字符串

时间:2016-11-29 20:57:28

标签: javascript

我一直在寻找一种方法来做到这一点,但似乎无法找到任何东西,我有不同的配置对象,我需要将其保存为变量中的文本,稍后进行一些处理,这里是一个样本:

对象

args.config.config = {
        next: null,
        final:[],
        delimiter: '~', header: false,
        step: function (row) {
            var item = {
                'line_code': row.data[0][0],
                'order': row.data[0][1]
            }
            args.config.config.final.push(item);
        },
        complete: function (result) {
            console.log('Reading data completed. Processing.');
            return args.config.config.next(null, args.config.config.final);
        },
        error: function () {
            console.log('There was an error parsing');
        }'
    }

我需要将其保存为字符串,例如:

args.config.config = "{object goes here}";

不将所有内容放在一条巨线上或添加断行符,因为稍后会对其进行解析以便在配置中使用,这样会搞砸任何想法?

更新 因此将它们更改为文本可能不是最佳解决方案,这些配置将存储在mongo数据库中,因此可能需要它们(我还没有尝试过)。

我遇到的另一个问题是在配置对象中我有这个:

final.push(item)

return next(null, final)

将使用配置对象在另一个文件中定义:

其他档案:

exports.parse = function(args, next){//next is what I need to call in the config

    var final = []; //this is the final referred to in the config object
    ....
    Baby.parse(data, args.config)
}

所以返回next(null,final)和final.push(result)必须引用新文件中的var / function,但我不知道如何让它工作,这就是为什么我必须在config对象中添加一个final数组和一个null next函数,然后像这样分配它:

exports.parse = function(args, next){
    args.config.next = next;
    ....
    Baby.parse(data, args.config)
}

对象用丑陋的行来调用它:

   return args.config.config.next(null, args.config.config.final);

如果有人解决这个问题,我们将非常感激。

1 个答案:

答案 0 :(得分:3)

  

如果您使用 JSON.stringify with a "replacer" function 和   JSON.parse with a "reviver" function以及new Function(),您可以这样做:

我不确定我是否已按照您提出的第二个(更新的)问题进行操作。将对象解析回对象后,为什么只能在调用任何对象的方法之前将nextfinal属性初始化为有效对象?您甚至可以在该方法中添加测试,以便在返回任何内容之前检查是否存在finalnext



var myObj = {
        next: null,
        final:[],
        delimiter: '~', 
        header: false,
        step: function (row) {
            var item = {
                'line_code': row.data[0][0],
                'order': row.data[0][1]
            };
            args.config.config.final.push(item);
        },
        complete: function (result) {
            console.log('Reading data completed. Processing.');
            return args.config.config.next(null, args.config.config.final);
        },
        error: function () {
            console.log('There was an error parsing');
        }
    };

// Stringify the object using a replacer function that will explicitly
// turn functions into strings
var myObjString = JSON.stringify(myObj, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});

// Now, parse back into an object with a reviver function to
// test for function values and create new functions from them:
var obj = JSON.parse(myObjString, function(key, val){
  
    // Make sure the current value is not null (is a string)
    // and that the first characters are "function"
    if(typeof val === "string" && val.indexOf('function') === 0){

      // Isolate the argument names list
      var start = val.indexOf("(") + 1;
      var end = val.indexOf(")");     
      var argListString = val.substring(start,end).split(",");
      
      // Isolate the body of the function
      var body = val.substr(val.indexOf("{"), val.length - end + 1);
      
      // Construct a new function using the argument names and body
      // stored in the string:
      return new Function(argListString, body);
      
    } else {
      // Non-function property, just return the value
      return val;
    } 
  }
);

// Test the method:
obj.error(); // 'There was an error parsing' is written to console.

// Examine the object:
console.log(obj);