本文介绍了如何在自定义toJSON方法中使用JSON.stringify?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,JSON.stringify提供了一个转换JS对象的好方法:

So, JSON.stringify provides a great way to turn a JS object like:

var baz = {"foo":1, "bar":someFunction};

输入JSON字符串,如:

in to a JSON string like:

{"foo":1}

它是这样做的一个可选的第二个参数,用于控制应序列化的字段:

It does this with an optional second argument that controls which fields should be serialized:

JSON.stringify(baz, ["foo"]);

这很好,但是有问题。假设您的baz实际上是另一个对象的属性,并且您想序列化该另一个对象:

That's great, but there's a problem. Let's say your "baz" is actually the property of another object, and you want to serialize that other object:

someObject.baz = {"foo":1, "bar":someFunction};
JSON.stringify(someObject, ["baz"]);

好吧,通常你只需要在baz上定义一个toJSON方法,例如:

Well, normally you would just define a toJSON method on baz, eg.:

someObject.baz = {"foo":1, "bar":someFunction};
someObject.baz.toJSON = function() { /* logic to "toJSON" baz*/ }
JSON.stringify(someObject, ["baz"]);

现在,正如我前面提到的,我们已经有了toJSONbaz的完美逻辑:

Now, as I mentioned earlier, we have the perfect logic to "toJSON" baz already:

someObject.baz.toJSON = function() {
    return JSON.stringify(baz, ["foo"]);
}

但是如果你试着把它放到你的toJSON中,你会得到一个递归错误,因为stringify将触发toJSON,这将触发stringify,这将...: - (

but if you try putting that in to your toJSON, you'll get a recursion error, because stringify will trigger the toJSON, which will trigger the stringify, which will ... :-(

你可以解决这个问题:

someObject.baz.toJSON = function() {
    var oldToJON = this.toJSON;
    this.toJSON = null;
    var ret = JSON.stringify(baz, ["foo"]);
    this.toJSON = oldToJON;
    return ret;
}

但是......这似乎是错误的。所以,我的问题是:你有什么办法可以利用漂亮的建筑 - 在JSON.stringify 里面一个对象的toJSON方法的序列化能力(在stringify操作期间不必隐藏toJSON方法本身)?

But ... that just seems wrong. So, my question is: is there any way you can utilize the nifty built-in serialization power of JSON.stringify inside a toJSON method of an object (without having to hide the toJSON method itself during the stringify operation)?

推荐答案

说:

因此,您只需返回要序列化的值。在您的情况下, baz.toJSON 应该只返回要序列化的 baz 对象的部分:

So you are simply expected to return the value that you want serialized. In your case, baz.toJSON should simply return the portion of the baz object that you want serialized:

someObject.baz.toJSON = function() {
  return { foo: this.foo };
};

这篇关于如何在自定义toJSON方法中使用JSON.stringify?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:40