title: How do you use JSON.stringify in a custom toJSON method?
body: <p>So, JSON.stringify provides a great way to turn a JS object like:</p>
  
  <pre><code>var baz = {"foo":1, "bar":someFunction};
  </code></pre>
  
  <p>in to a JSON string like:</p>
  
  <pre><code>{"foo":1}
  </code></pre>
  
  <p>It does this with an optional second argument that controls which fields should be serialized:</p>
  
  <pre><code>JSON.stringify(baz, ["foo"]);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>someObject.baz = {"foo":1, "bar":someFunction};
  JSON.stringify(someObject, ["baz"]);
  </code></pre>
  
  <p>Well, normally you would just define a toJSON method on baz, eg.:</p>
  
  <pre><code>someObject.baz = {"foo":1, "bar":someFunction};
  someObject.baz.toJSON = function() { /* logic to "toJSON" baz*/ }
  JSON.stringify(someObject, ["baz"]);
  </code></pre>
  
  <p>Now, as I mentioned earlier, we have the perfect logic to "toJSON" baz already:</p>
  
  <pre><code>someObject.baz.toJSON = function() {
      return JSON.stringify(baz, ["foo"]);
  }
  </code></pre>
  
  <p>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 ... :-(</p>
  
  <p>You can work around this with a hack:</p>
  
  <pre><code>someObject.baz.toJSON = function() {
      var oldToJON = this.toJSON;
      this.toJSON = null;
      var ret = JSON.stringify(baz, ["foo"]);
      this.toJSON = oldToJON;
      return ret;
  }
  </code></pre>
  
  <p>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 <em>inside</em> a toJSON method of an object (without having to hide the toJSON method itself during the stringify operation)?</p>