2

I'd sure like to be able to add this:

Object.prototype.toJson = function() { this.toJson = undefined; return JSON.stringify(this); }

But it gets all circular reference-y. I still want to be able to write .toJson() all over the everywhere.

nclu
  • 1,057
  • 1
  • 8
  • 19
  • Maybe with out that this.toJson = undefined in there. That was messing around that ended up in my clipboard. – nclu Oct 08 '13 at 23:40
  • Just drop the `this.toJson = undefined;`...what are you trying to accomplish with that? – Ethan Brown Oct 08 '13 at 23:40
  • Without it still yeilds: Uncaught TypeError: Converting circular structure to JSON it was a lame attempt to make that go away. – nclu Oct 08 '13 at 23:43
  • Just tested this in the console of chrome, and it works fine here. `Object.prototype.toString = function() {return JSON.stringify(this);};var j = {a: 'b'};j.toString()` yields `"{"a":"b"}"` in the console window. – atomman Oct 08 '13 at 23:50
  • The basic `Object` contains references to itself that `JSON.stringify()` can't resolve. You need to make sure the data structure you are are trying to encode is a valid data structure for encoding. – Mike Brant Oct 08 '13 at 23:51
  • 1
    @nclu: Can you please show us on what object you tried `.toJson()`? Probably it just *has* a circular reference. – Bergi Oct 08 '13 at 23:55
  • 2
    Don't forget to have a look at [How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop](http://stackoverflow.com/questions/13296340/how-to-define-method-in-javascript-on-array-prototype-and-object-prototype-so-th) – Bergi Oct 08 '13 at 23:57
  • Seems to work fine. http://jsfiddle.net/UfZmr/1/ – Yuriy Galanter Oct 09 '13 at 22:00
  • The error actually seems to come in when other libraries are later loaded. Moment.js and KendoUI both are triggering the circular reference. At this point I'm thinking that modifying the Object prototype isn't a very good idea. It'd be nice if objects could just serialize themselves and handle circularity in some magical elegant fashion. – nclu Oct 10 '13 at 15:52

1 Answers1

1

Seems to work fine.

Object.prototype.toJson = function() { this.toJson = undefined; return JSON.stringify(this); }

The error actually seems to come in when other libraries are later loaded. Moment.js and KendoUI both are triggering the circular reference. At this point I'm thinking that modifying the Object prototype isn't a very good idea. It'd be nice if objects could just serialize themselves and handle circularity in some magical elegant fashion

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265