Javascript JSON.stringify 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6754919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.stringify function
提问by Sorin Buturugeanu
I have an object that has some properties and methods, like so:
我有一个具有一些属性和方法的对象,如下所示:
{name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628}
and I have to pass this object to another function. So I tried to use JSON.stringify(obj) but the load function (which of course isn't empty, this is just for the purpose of this example) is being "lost".
我必须将此对象传递给另一个函数。所以我尝试使用 JSON.stringify(obj) 但加载函数(当然不是空的,这只是为了这个例子的目的)正在“丢失”。
Is there any way to stringify
and object and maintain the methods it has?
有什么方法可以stringify
反对和维护它所拥有的方法吗?
Thanks!
谢谢!
采纳答案by David Titarenco
Why exactly do you want to stringify the object? JSON doesn't understand functions (and it's not supposed to). If you want to pass around objects why not do it one of the following ways?
为什么要对对象进行字符串化?JSON 不理解函数(它不应该理解)。如果您想传递对象,为什么不使用以下方法之一?
var x = {name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628};
function y(obj) {
obj.load();
}
// works
y({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628});
// "safer"
y(({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}));
// how it's supposed to be done
y(x);
回答by chjj
There is a way to serialize a function in JS, but you'll have to eval it on the other side and it will also lose access to it's original scope. A way to do it would be:
有一种方法可以在 JS 中序列化一个函数,但是您必须在另一端对其进行评估,并且它也将无法访问它的原始作用域。一种方法是:
JSON.stringify(objWithFunction, function(key, val) {
if (typeof val === 'function') {
return val + ''; // implicitly `toString` it
}
return val;
});
There are some legitimate uses for what you're asking despite what people are posting here, however, it all depends on what you're going to be using this for. There may be a better way of going about whatever it is you're trying to do.
尽管人们在这里发布了什么,但您所询问的内容有一些合法用途,但是,这一切都取决于您将要使用它做什么。可能有更好的方法来处理您正在尝试做的任何事情。
回答by vadimk
In fact, It's very easy to serealize / parse javascript object with methods.
实际上,使用方法序列化/解析javascript对象非常容易。
Take a look at JSONfnplugin.
看看JSONfn插件。
http://www.eslinstructor.net/jsonfn/
http://www.eslinstructor.net/jsonfn/
Hope this helps.
希望这可以帮助。
-Vadim
-瓦迪姆
回答by RossBille
Not something I would ever do but it is worth mentioning that there are ways to stringify function (i.e. it is not impossible).
不是我会做的事情,但值得一提的是,有一些方法可以对函数进行字符串化(即并非不可能)。
Take the following:
采取以下措施:
var func = function(){console.log('logged')};
var strFunc = func.toString();
//then
var parsedFunc = eval('('+strFunc+')');
parsedFunc();
//or simply
eval('('+strFunc+')()');
//or
eval('('+strFunc+')')();
//or
eval('var anotherFunc='+strFunc);
anotherFunc()
The above with an overridden toJSON()
can achieve a shallow stringified function;
上面带有覆盖的toJSON()
可以实现一个浅的字符串化函数;
DISCLAIMER: look into thisand other articles and make your own decision before using eval()
免责声明:在使用之前查看这篇文章和其他文章并做出自己的决定eval()
回答by streaver91
Here's some code I have used in my previous projects, maybe useful?
这是我在以前的项目中使用的一些代码,也许有用?
// Similar to JSON.stringify(), with three major differences:
// (1) It also wrap functions
// (2) Upon execution, it expose an object, nl, into the scope
// (3) Results are minified by 'uglify-js'
var bundle = function(obj) {
var type = typeof obj;
if(type === 'string') return '\'' + obj + '\'';
if(type === 'boolean' || type === 'number') return obj;
if(type === 'function') return obj.toString();
var ret = [];
for(var prop in obj) {
ret.push(prop + ': ' + bundle(obj[prop]));
}
return '{' + ret.join(',') + '}';
};
var ret = 'var nl = ' + bundle(nl);
ret = require('uglify-js').minify(ret, {fromString: true}).code;
fs.writeFileSync('nl.js', ret);
One Caveat when using this is that if the function uses anything in external closure, it won't work, ie: ... obj: {..., key: (function() {...var a = 10;... return function() {... some code uses 'a'...})()}
使用它时的一个警告是,如果函数在外部闭包中使用任何东西,它将不起作用,即:... obj: {..., key: (function() {...var a = 10;. .. return function() {... 一些代码使用 'a'...})()}