简体   繁体   English

如何在自定义toJSON方法中使用JSON.stringify?

[英]How do you use JSON.stringify in a custom toJSON method?

So, JSON.stringify provides a great way to turn a JS object like: 因此,JSON.stringify提供了一种转换JS对象的好方法,例如:

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

in to a JSON string like: 输入JSON字符串,例如:

{"foo":1}

It does this with an optional second argument that controls which fields should be serialized: 它使用一个可选的第二个参数来执行此操作,该参数控制应序列化哪些字段:

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

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: 假设您的“ baz”实际上是另一个对象的属性,并且您想要序列化另一个对象:

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

Well, normally you would just define a toJSON method on baz, eg.: 好吧,通常您只需要在baz上定义一个toJSON方法,例如:

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

Now, as I mentioned earlier, we have the perfect logic to "toJSON" baz already: 现在,正如我前面提到的,我们已经有了完美的逻辑来“ toJSON” baz:

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

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 ... :-( 但是,如果您尝试将其放入toJSON中,则会收到递归错误,因为stringify将触发toJSON,这将触发stringify,这将... :-(

You can work around this with a hack: 您可以通过以下方法解决此问题:

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

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)? 所以,我的问题是:有什么方法可以利用对象的toJSON方法内部的JSON.stringify内置的强大序列化功能(而在stringify操作期间不必隐藏toJSON方法本身)?

Crockford's json2.js says: 克罗克福德的json2.js说:

A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. toJSON方法不会序列化:它返回由应该被序列化的名称/值对表示的值,或者如果没有任何序列化则返回undefined。

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: 在您的情况下, baz.toJSON应该只返回要序列化的baz对象的一部分:

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

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

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