JavaScript - 使用方法将对象保存为字符串 [英] JavaScript - Save object with methods as a string

查看:160
本文介绍了JavaScript - 使用方法将对象保存为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been looking around for a way to do this but can't seem to find anything, I have different configuration objects that I need to save as a text in variables for some processing later on, here is a sample:

对象:

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

我需要将其保存为字符串,所以类似于:

I need to save this as a string, so something like:

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

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

Without putting everything on one giant line or adding break line characters as this will be parsed later to be used in a config, and that will mess things up, any ideas?

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

UPDATE: So changing them into text may not be the best solution, these configs will be stored in a mongo database, so it may take them as is (I have not tried it yet).

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

One of the other problems I was running into was that in the config object I had this:

final.push(item)

return next(null, final)

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

Which will be defined in another file using the config object:

其他档案:

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,但我有不知道如何让它工作,这就是为什么我必须在配置对象中添加一个最终数组和一个空的下一个函数,然后像这样分配:

So the return next(null, final) and final.push(result) have to refer the the var / function in the new file, but I have no idea how to get that to work, that't why I had to add a final array in the config object and a null next function, then assign it like so:

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

对象用丑陋的行调用它:

the object was calling it with the ugly line:

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

如果有人能解决这个问题,我们将不胜感激。

If anyone has a way around this, it would be much appreciated.

推荐答案


如果您使用 JSON.stringify 带有replacer功能
JSON.parse 带有reviver功能 以及 new Function() ,你可以这样做:

If you use JSON.stringify with a "replacer" function and JSON.parse with a "reviver" function along with new Function(), you can do it:

我不确定我是否正在关注你的第二个(更新的)问题。一旦将对象解析回对象,为什么不能只将 next final 属性初始化为有效在调用任何对象的方法之前的对象?您甚至可以在该方法中添加测试,以便在返回任何内容之前检查是否存在 final next

I'm not sure I'm following the second (updated) question you have. Once the object is parsed back into an object, why can't you just initialize the next and final properties to valid objects before calling any of the object's methods? You can even add tests into that method that checks for the existence of final and next before returning anything.

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);

这篇关于JavaScript - 使用方法将对象保存为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆