简体   繁体   English

JSON.stringify function

[英]JSON.stringify function

I have an object that has some properties and methods, like so:我有一个 object 有一些属性和方法,像这样:

{name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628}

and I have to pass this object to another function.我必须将这个 object 传递给另一个 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) 但是负载 function (当然不是空的,这只是为了这个例子的目的)正在“丢失”。

Is there any way to stringify and object and maintain the methods it has?有什么方法可以对 object 进行stringify并维护它的方法吗?

Thanks!谢谢!

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.有一种方法可以在 JS 中序列化 function,但您必须在另一侧对其进行评估,并且它也将无法访问其原始 scope。 A way to do it would be:一种方法是:

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.无论您尝试做什么,都可能有更好的方法。

In fact, It's very easy to serealize / parse javascript object with methods .事实上,使用方法很容易实现/解析 javascript object

Take a look at JSONfn plugin.看看JSONfn插件。

http://www.eslinstructor.net/jsonfn/ http://www.eslinstructor.net/jsonfn/

Hope this helps.希望这可以帮助。

-Vadim -瓦迪姆

Why exactly do you want to stringify the object?为什么要对 object 进行字符串化? JSON doesn't understand functions (and it's not supposed to). JSON 不理解函数(而且不应该)。 If you want to pass around objects why not do it one of the following ways?如果您想传递对象,为什么不使用以下方法之一呢?

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

Not something I would ever do but it is worth mentioning that there are ways to stringify function (ie it is not impossible).不是我会做的事情,但值得一提的是,有一些方法可以对 function 进行字符串化(即并非不可能)。

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()可以实现浅字符串化 function;

DISCLAIMER : look into this and other articles and make your own decision before using eval()免责声明:查看这篇文章和其他文章并在使用eval()之前做出自己的决定

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'...})()}使用它时需要注意的是,如果 function 在外部闭包中使用任何东西,它将不起作用,即:... obj: {..., key: (function() {...var a = 10;. .. return function() {... some code uses 'a'...})()}

You can override the toJSON() method, which serializes the function to another object.您可以覆盖toJSON()方法,该方法将 function 序列化为另一个 object。 Here is an example which converts the function to a string:这是一个将 function 转换为字符串的示例:

 Function.prototype.toJSON = Function.prototype.toString; var o = {name: "FirstName", age: "19", load: function () {}, uniq: 0.5233059714082628}; console.log(JSON.stringify(o,null,4))

If you wanted to print, say, the property descriptors instead:如果你想打印,比如说,属性描述符:

 Function.prototype.toJSON = function() { return Object.getOwnPropertyDescriptors(this); } var o = {name: "FirstName", age: "19", load: function () {}, uniq: 0.5233059714082628}; console.log(JSON.stringify(o,null,4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM