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

前端 未结 1 1893
离开以前
离开以前 2020-12-14 16:39

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

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

in to a JSON string like:

1条回答
  •  被撕碎了的回忆
    2020-12-14 17:40

    Crockford's json2.js says:

    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.

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

    0 讨论(0)
提交回复
热议问题