与JSON进行序列化和反序列化 [英] Serializing and deserializing functions to and from JSON

查看:130
本文介绍了与JSON进行序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您具有以下条件:

function myfunc() {
  // JS code
}

var args = '{ "strfield": "hello world", "numfield": 10, "funcfield": myfunc }';

问题:在将args变量提交给JSON解析器之前如何处理,以便将myfunc替换为myfunc.toString()的结果(即函数的主体)?所提出的解决方案应该适用于任意函数和此类准JSON字符串.

The problem: how do you process the args variable before submitting it to the JSON parser so that myfunc is replaced with the result of myfunc.toString() (that is, the body of the function)? The proposed solution should work on arbitrary functions and such quasi-JSON strings.

推荐答案

喜欢吗?我必须更改它,因为您拥有的不是有效的JSON字符串,因为myfunc没有双引号.所以我添加了这些.

Like this? I had to change it because what you have isn't a valid JSON string since myfunc doesn't have double quotes. So I added those.

这将解析它,获取funcfield的值,找到函数(尽管它假定它位于全局上下文中),调用toString()更新funcfield的值,然后将其重新字符串化为JSON.

This parses it, gets the value of funcfield, finds the function (although it assumes it is in the global context), calls toString() updating the value of funcfield, the re-stringifies it as JSON.

示例: http://jsfiddle.net/patrick_dw/QUR6Z/

var myfunc = function() {
    alert('hi');
};

var args = '{ "strfield": "hello world", "numfield": 10, "funcfield": "myfunc" }';
var parsed = JSON.parse( args );

parsed.funcfield = window[parsed.funcfield].toString();
var stringified = JSON.stringify( parsed );

alert(stringified);

这是什么意思?

我想您可以使用当前上下文,只要该上下文包含在拥有函数的上下文中即可.

I guess you could use the current context, as long as that context is contained within the context that owns the function.

parsed.funcfield = this[parsed.funcfield].toString();

或者如果不能用双引号括住函数名称,则可以使用eval来代替,如果您确定数据是安全的.

Or if you can't double quote the function name, you could use eval instead if you're certain the data is safe.

示例:: http://jsfiddle.net/patrick_dw/QUR6Z/1/

var args = '{ "strfield": "hello world", "numfield": 10, "funcfield": myfunc }';
window.eval( 'var parsed = ' + args );

parsed.funcfield = parsed.funcfield.toString();
var stringified = JSON.stringify( parsed );

alert(stringified);

这篇关于与JSON进行序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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